Ejemplo n.º 1
0
  @SuppressLint("NewApi")
  public void changeCameraFacing() {
    // 切换前后摄像头
    int cameraCount = 0;
    CameraInfo cameraInfo = new CameraInfo();
    cameraCount = Camera.getNumberOfCameras(); // 得到摄像头的个数

    for (int i = 0; i < cameraCount; i++) {
      Camera.getCameraInfo(i, cameraInfo); // 得到每一个摄像头的信息
      if (cameraPosition == 1) {
        // 现在是后置,变更为前置
        if (cameraInfo.facing
            == Camera.CameraInfo
                .CAMERA_FACING_FRONT) { // 代表摄像头的方位,CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
          mCamera.setPreviewCallback(null);
          mCamera.stopPreview(); // 停掉原来摄像头的预览
          mCamera.release(); // 释放资源
          mCamera = null; // 取消原来摄像头
          mCamera = Camera.open(i); // 打开当前选中的摄像头
          try {
            mCamera.setPreviewDisplay(mHolder); // 通过surfaceview显示取景画面
            initParameters();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          mCamera.startPreview(); // 开始预览
          cameraPosition = 0;
          break;
        }
      } else {
        // 现在是前置, 变更为后置
        if (cameraInfo.facing
            == Camera.CameraInfo
                .CAMERA_FACING_BACK) { // 代表摄像头的方位,CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
          mCamera.setPreviewCallback(null);
          mCamera.stopPreview(); // 停掉原来摄像头的预览
          mCamera.release(); // 释放资源
          mCamera = null; // 取消原来摄像头
          mCamera = Camera.open(i); // 打开当前选中的摄像头
          try {
            mCamera.setPreviewDisplay(mHolder); // 通过surfaceview显示取景画面
            initParameters();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          mCamera.startPreview(); // 开始预览
          cameraPosition = 1;
          break;
        }
      }
    }
  }
  @Override
  public void onPictureTaken(byte[] data, Camera camera) {

    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      Log.d(DEBUG_TAG, "Can't create directory to save image.");
      mToast.setText("Can't create directory to save image.");
      mToast.show();
      return;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = "Picture_" + date + "_" + photoCounter + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    double lat = 0;
    double lon = 0;

    gpsHelper.getMyLocation();

    if (gpsHelper.isGPSenabled()) {
      lat = gpsHelper.getLatitude();
      lon = gpsHelper.getLongitude();

      String debugGps = String.valueOf(lat) + " " + String.valueOf(lon);
      this.tv.setText(debugGps);
      Log.d(DEBUG_TAG, debugGps);
      mToast.setText(debugGps);
      mToast.show();
    } else {
      Log.d(DEBUG_TAG, "GPS is not enabled.");
      mToast.setText("GPS is not enabled.");
      mToast.show();
    }

    (new WriteToFileTask(data, filename, lat, lon)).execute();

    photoCounter++;
    if (photoCounter < quantityPerStep) {
      camera.startPreview();
      camera.takePicture(null, null, this);
    } else {
      photoCounter = 0;
    }
    camera.startPreview();
  }
Ejemplo n.º 3
0
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
      case R.id.switch_cam:
        // Release this camera -> mCameraCurrentlyLocked
        if (mCamera != null) {
          mCamera.stopPreview();
          mPreview.setCamera(null);
          mCamera.release();
          mCamera = null;
        }

        // Acquire the next camera and request Preview to reconfigure
        // parameters.
        mCamera = Camera.open((mCameraCurrentlyLocked + 1) % mNumberOfCameras);
        mCameraCurrentlyLocked = (mCameraCurrentlyLocked + 1) % mNumberOfCameras;
        mPreview.switchCamera(mCamera);

        // Start the preview
        mCamera.startPreview();
        return true;
      case android.R.id.home:
        Intent intent = new Intent(this.getActivity(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

      default:
        return super.onOptionsItemSelected(item);
    }
  }
  private boolean openCamera(int id) {
    boolean result = false;
    cameraId = id;
    releaseCamera();
    try {
      camera = Camera.open(cameraId);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (camera != null) {
      try {
        setUpCamera(camera);
        camera.setErrorCallback(
            new ErrorCallback() {

              @Override
              public void onError(int error, Camera camera) {}
            });
        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();
        result = true;
      } catch (IOException e) {
        e.printStackTrace();
        result = false;
        releaseCamera();
      }
    }
    return result;
  }
Ejemplo n.º 5
0
 /** Asks the camera hardware to begin drawing preview frames to the screen. */
 public void startPreview() {
   if (camera != null && !previewing) {
     camera.setDisplayOrientation(90);
     camera.startPreview();
     previewing = true;
   }
 }
Ejemplo n.º 6
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + h);
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.
    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    // set preview size and make any resize, rotate or reformatting changes here
    // start preview with new settings
    try {
      Camera.Parameters parameters = mCamera.getParameters();

      /* INSERT ZOOM HERE */

      parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
      parameters.setRotation(90);
      mCamera.setParameters(parameters);
      mCamera.setDisplayOrientation(90);

      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
Ejemplo n.º 7
0
 /** **************************************************************** about Camera */
 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
   Log.d(TAG, "---->>>>>>>>>> surfaceChanged()");
   if (holder.getSurface() == null) {
     Log.d(TAG, "---- surfaceChanged(),  holder.getSurface() == null");
     return;
   }
   mSurfaceHolder = holder;
   try {
     hasCamera = true;
     nocamera.setVisibility(View.GONE);
     mCameraDevice = Camera.open(mCurrentCameraId);
   } catch (Exception e) {
     hasCamera = false;
     nocamera.setVisibility(View.VISIBLE);
     mSwitchBut.setVisibility(View.GONE);
     Log.e(TAG, " ____________- camera error");
     return;
   }
   if (mHardwareRotation == 0) // XXX
   mCameraDevice.setDisplayOrientation(90);
   if (mCurrentCameraId == 1) mCameraDevice.setDisplayOrientation(270); // XXX
   try {
     mCameraDevice.setPreviewDisplay(mSurfaceHolder);
   } catch (IOException e) {
     e.printStackTrace();
   }
   mCameraDevice.startPreview();
 }
Ejemplo n.º 8
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if (mHolder.getSurface() == null) {
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    if (mSupportedPreviewSizes != null) {
      mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, w, h);
    }

    // start preview with new settings
    try {

      mCamera.setPreviewDisplay(mHolder);

      Parameters params = mCamera.getParameters();
      // params.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
      params.setPreviewSize(
          mSupportedPreviewSizes.get(0).width, mSupportedPreviewSizes.get(0).height);
      mCamera.setParameters(params);
      mCamera.startPreview();

      Log.d(TAG, "Preview Size: " + mPreviewSize.width + "X" + mPreviewSize.height);

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    /*
     * If your preview can change or rotate, take care of those events here.
     * Make sure to stop the preview before resizing or reformatting it.
     */
    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    try {
      // Hard code camera surface rotation 90 degs to match Activity view in portrait
      mCamera.setDisplayOrientation(90);

      mCamera.setPreviewDisplay(mHolder);
      mCamera.setPreviewCallback(previewCallback);
      mCamera.startPreview();
      mCamera.autoFocus(autoFocusCallback);
    } catch (Exception e) {
      Log.d("DBG", "Error starting camera preview: " + e.getMessage());
    }
  }
  public void startCamera() {
    mCamera = Camera.open();
    try {
      Camera.Parameters parameters = mCamera.getParameters();
      Display display =
          ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

      if (display.getRotation() == Surface.ROTATION_0) {
        // parameters.setPreviewSize(height, width);
        mCamera.setDisplayOrientation(90);
      }

      if (display.getRotation() == Surface.ROTATION_90) {
        // parameters.setPreviewSize(width, height);
      }

      if (display.getRotation() == Surface.ROTATION_180) {
        // parameters.setPreviewSize(height, width);
      }

      if (display.getRotation() == Surface.ROTATION_270) {
        // parameters.setPreviewSize(width, height);
        mCamera.setDisplayOrientation(180);
      }
      mCamera.setParameters(parameters);
      mCamera.setPreviewDisplay(surface_holder);
      mCamera.startPreview();
      cameraRunning = true;
    } catch (IOException exception) {
      mCamera.release();
      mCamera = null;
    }
  }
Ejemplo n.º 11
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    mHolder.setFixedSize(w, h);
    // Start the preview
    Parameters params = mCamera.getParameters();
    previewHeight = params.getPreviewSize().height;
    previewWidth = params.getPreviewSize().width;
    previewFormat = params.getPreviewFormat();

    // Crop the edges of the picture to reduce the image size
    r =
        new Rect(
            previewShrink,
            previewShrink,
            previewWidth - previewShrink,
            previewHeight - previewShrink);

    mCallbackBuffer = new byte[497664];

    mCamera.setParameters(params);
    mCamera.setPreviewCallbackWithBuffer(
        new PreviewCallback() {
          public void onPreviewFrame(byte[] imageData, Camera arg1) {
            convWorker.nextFrame(imageData);
          }
        });
    mCamera.addCallbackBuffer(mCallbackBuffer);
    mCamera.startPreview();
    setTorchMode(mTorchMode);
  }
Ejemplo n.º 12
0
  public void surfaceChanged(SurfaceHolder mholder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      Log.d(LOG_TAG, "Unable to stop preview");
    }
    Parameters p = mCamera.getParameters();
    mCamera.setDisplayOrientation(90);
    mCamera.setParameters(p);
    Log.d(LOG_TAG, "Surface changed");

    // set preview size and make any resize, rotate or
    // reformatting changes here

    // start preview with new settings
    try {
      mCamera.setPreviewDisplay(mholder);
      mCamera.startPreview();
      Log.d(LOG_TAG, "Starting camera preview ");
    } catch (IOException e) {
      Log.d(LOG_TAG, "Error starting camera preview " + e.getMessage());
    } catch (Exception e) {
      Log.d(LOG_TAG, "Error 2 starting camera preview " + e.getMessage());
    }
  }
Ejemplo n.º 13
0
  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    // Sets preview size.
    Camera.Parameters parameters = mCamera.getParameters();
    List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
    Camera.Size cs = sizes.get(0);
    parameters.setPreviewSize(cs.width, cs.height);
    mCamera.setParameters(parameters);

    // start preview with new settings
    try {
      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
    Log.e(TAG, "SurfaceChanged.");
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.v("FlashlightService", "Starting Flash");
    if (cam != null) return START_NOT_STICKY;
    try {
      cam = Camera.open();
      Parameters p = cam.getParameters();
      List<String> flashes = p.getSupportedFlashModes();
      if (flashes == null) return error(this, R.string.err_available);
      if (flashes.contains(Parameters.FLASH_MODE_TORCH))
        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
      else if (flashes.contains(Parameters.FLASH_MODE_ON)) p.setFlashMode(Parameters.FLASH_MODE_ON);
      else return error(this, R.string.err_available);
      cam.setParameters(p);
      // Needed for some devices.
      cam.setPreviewTexture(new SurfaceTexture(0));
      // Needed for some more devices.
      cam.startPreview();

      // Keep phone awake with screen off
      wl =
          ((PowerManager) getSystemService(Context.POWER_SERVICE))
              .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FlashlightService");
      if (wl != null && !wl.isHeld()) wl.acquire();
      return START_NOT_STICKY;
    } catch (Exception e) {
      return error(this, R.string.err_access);
    }
  }
Ejemplo n.º 15
0
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

          // another way to create and write out a file, instead of what was done in picCapture
          File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
          if (pictureFile == null) {
            Log.d(TAG, "Error creating media file, check storage permissions: ");
            return;
          }
          Log.d(TAG, "File created as:" + pictureFile);
          // write out the file.
          try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
          } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
          } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
          }

          // new tell the system that the file exists , so it will show up in
          // gallery/photos/whatever
          ContentValues values = new ContentValues();
          values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
          values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
          values.put(MediaStore.MediaColumns.DATA, pictureFile.toString());
          getActivity()
              .getContentResolver()
              .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

          camera.startPreview(); // start backup the preview, once we have taken the picture.
        }
Ejemplo n.º 16
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.
    Log.i(TAG, "srface changed");
    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    // set preview size and make any resize, rotate or
    // reformatting changes here

    // start preview with new settings
    try {
      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
Ejemplo n.º 17
0
  // Called when holder has changed
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

    Camera.Parameters parameters = camera.getParameters();
    List<String> focusModes = parameters.getSupportedFocusModes();
    if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
      Log.d("camera", "focus_mode_auto");
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    } else {
      Log.d("camera", "focus_mode_macro");
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
    }
    Log.d("camera", "orientation: " + getResources().getConfiguration().orientation);
    int orientation = getResources().getConfiguration().orientation;
    switch (orientation) {
      case Surface.ROTATION_0:
        Log.d("camera", "ROTATION_0");
        camera.setDisplayOrientation(180);
        break;
      case Surface.ROTATION_90:
        Log.d("camera", "ROTATION_90");
        camera.setDisplayOrientation(90);
        break;
      case Surface.ROTATION_180:
        Log.d("camera", "ROTATION_180");
        camera.setDisplayOrientation(0);
        break;
      case Surface.ROTATION_270:
        Log.d("camera", "ROTATION_270");
        camera.setDisplayOrientation(270);
        break;
    }

    camera.setParameters(parameters);
    camera.startPreview();
  }
Ejemplo n.º 18
0
  protected synchronized void updateCamera() throws RuntimeException {

    // The camera is already correctly configured
    if (mUpdated) return;

    if (mPreviewStarted) {
      mPreviewStarted = false;
      mCamera.stopPreview();
    }

    Parameters parameters = mCamera.getParameters();
    mQuality = VideoQuality.determineClosestSupportedResolution(parameters, mQuality);
    int[] max = VideoQuality.determineMaximumSupportedFramerate(parameters);

    double ratio = (double) mQuality.resX / (double) mQuality.resY;
    mSurfaceView.requestAspectRatio(ratio);

    parameters.setPreviewFormat(mCameraImageFormat);
    parameters.setPreviewSize(mQuality.resX, mQuality.resY);
    parameters.setPreviewFpsRange(max[0], max[1]);

    try {
      mCamera.setParameters(parameters);
      mCamera.setDisplayOrientation(mOrientation);
      mCamera.startPreview();
      mPreviewStarted = true;
      mUpdated = true;
    } catch (RuntimeException e) {
      destroyCamera();
      throw e;
    }
  }
Ejemplo n.º 19
0
  @Override
  public void onPictureTaken(byte[] data, Camera camera) {

    String filename = makeFileName();

    if (filename == "") {
      return;
    }

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();

      Toast.makeText(context, "New Image saved: ", Toast.LENGTH_LONG).show();
    } catch (Exception error) {
      // write error to logcat
      Log.d(DEBUG_TAG, "File" + filename + "not saved: " + error.getMessage());
      // toast to inform user of issue
      Toast.makeText(context, "Image could not be saved.", Toast.LENGTH_LONG).show();
    }

    // Restart the preview and re-enable the shutter button so that we can take another picture
    camera.startPreview();
    shutterButton.setEnabled(true);

    Intent previewIntent = new Intent(this, PreviewActivity.class);

    previewIntent.putExtra("PhotoFile", filename);

    startActivity(previewIntent);
  }
Ejemplo n.º 20
0
 private void changeMes() {
   preview.removeAllViews();
   mCamera.setPreviewCallback(new PreviewCallback(tv_values3, preview));
   mCamera.startPreview();
   mPreview = new CameraPreview(this, mCamera);
   preview.addView(mPreview);
 }
Ejemplo n.º 21
0
        public void onPictureTaken(byte[] data, Camera camera) {
          FileOutputStream outStream = null;
          Intent mIntent = new Intent();
          if (data != null) {
            try {
              // Gets the root of the external storage directory
              File root = Environment.getExternalStorageDirectory();
              // Check to see if the app can write to external storage
              if (root.canWrite()) {
                // Appends the directory we want to use
                File f = new File(root + "/DCIM/camera_example/");
                // Creates the directory
                f.mkdirs();

                // Create an output stream to actually write the data
                // from the image to the directory specified
                outStream =
                    new FileOutputStream(
                        root + "/DCIM/camera_example/" + System.currentTimeMillis() + ".jpg");
                outStream.write(data);
                outStream.close();
                Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
                Toast.makeText(ctx, "Picture saved...", Toast.LENGTH_SHORT).show();
              }
            } catch (FileNotFoundException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            } finally {
              mCamera.startPreview();
              setResult(FOTO_MODE, mIntent);
              notTakingPic = true;
            }
          }
        }
Ejemplo n.º 22
0
  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    try {
      // open the camera
      camera = Camera.open(1);
    } catch (RuntimeException e) {
      // check for exceptions
      System.err.println(e);
      return;
    }
    Camera.Parameters param;
    param = camera.getParameters();

    // modify parameter
    param.setPreviewSize(352, 288);
    camera.setParameters(param);
    try {
      // The Surface has been created, now tell the camera where to draw
      // the preview.
      camera.setPreviewDisplay(surfaceHolder);
      camera.setDisplayOrientation(90);
      camera.startPreview();
    } catch (Exception e) {
      // check for exceptions
      System.err.println(e);
      return;
    }
  }
Ejemplo n.º 23
0
  /**
   * Opens the camera and starts sending preview frames to the underlying detector. The preview
   * frames are not displayed.
   *
   * @throws IOException if the camera's preview texture or display could not be initialized
   */
  @RequiresPermission(Manifest.permission.CAMERA)
  public CameraSource start() throws IOException {
    synchronized (mCameraLock) {
      if (mCamera != null) {
        return this;
      }

      mCamera = createCamera();

      // SurfaceTexture was introduced in Honeycomb (11), so if we are running and
      // old version of Android. fall back to use SurfaceView.
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mDummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME);
        mCamera.setPreviewTexture(mDummySurfaceTexture);
      } else {
        mDummySurfaceView = new SurfaceView(mContext);
        mCamera.setPreviewDisplay(mDummySurfaceView.getHolder());
      }
      mCamera.startPreview();

      mProcessingThread = new Thread(mFrameProcessor);
      mFrameProcessor.setActive(true);
      mProcessingThread.start();
    }
    return this;
  }
Ejemplo n.º 24
0
 /**
  * Sets the up camera to be connected to GPUImage to get a filtered preview.
  *
  * @param camera the camera
  * @param degrees by how many degrees the image should be rotated
  * @param flipHorizontal if the image should be flipped horizontally
  * @param flipVertical if the image should be flipped vertically
  */
 public void setUpCamera(
     final Camera camera,
     final int degrees,
     final boolean flipHorizontal,
     final boolean flipVertical) {
   mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
   if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
     setUpCameraGingerbread(camera);
   } else {
     camera.setPreviewCallback(mRenderer);
     camera.startPreview();
   }
   Rotation rotation = Rotation.NORMAL;
   switch (degrees) {
     case 90:
       rotation = Rotation.ROTATION_90;
       break;
     case 180:
       rotation = Rotation.ROTATION_180;
       break;
     case 270:
       rotation = Rotation.ROTATION_270;
       break;
   }
   mRenderer.setRotationCamera(rotation, flipHorizontal, flipVertical);
 }
Ejemplo n.º 25
0
 /** 给摄像头设置好一系列相关参数,并开始预览 */
 private void initCamera() {
   azLog.log("isPreView", "" + isPreview);
   if (mCamera != null && !isPreview) {
     try {
       Camera.Parameters parameters = mCamera.getParameters();
       // 设置预览照片的大小
       parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
       // 设置预览照片时每秒显示多少帧的最小值和最大值
       parameters.setPreviewFpsRange(mFrameMin, mFrameMax);
       // 设置图片格式
       parameters.setPictureFormat(mImageFormat);
       // 设置JPG照片的质量
       parameters.set("jpeg-quality", mImageQuality);
       // 设置照片的大小
       parameters.setPictureSize(mPictureWidth, mPictureHeight);
       // 通过SurfaceView显示取景画面
       mCamera.setPreviewDisplay(mSurfaceHolder);
       // 开始预览
       mCamera.startPreview();
       azLog.log("AzCamera", "摄像头打开");
     } catch (IOException e) {
       e.printStackTrace();
     }
     isPreview = true;
   }
 }
Ejemplo n.º 26
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_camera);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mContext = CameraActivity.this;

    mUsersSQL = "select a.[CORPNO], a.[OPERNO], a.[OPERPASS] from b_opera a;";
    mSearchUsersSQL = "select count(*) from b_opera a where a.[CORPNO] = ? and a.[OPERNO] = ?;";
    mInsertOperaSQL = "INSERT INTO B_OPERA (CORPNO, OPERNO, OPERPASS) VALUES(?, ?, ?, ?, ?);";
    mInsertDownInfoSQL =
        "INSERT INTO B_LOGININFO (CORPNO, PROJDESC, DOWNURL, UPLOADURL, DBFILENAME, DOWNTIME) VALUES(?, ?, ?, ?, ?, ?);";
    mDownLoadInfoSQL =
        "select a.[CORPNO], a.[PROJDESC], a.[DOWNURL], a.[UPLOADURL], a.[DBFILENAME] from b_logininfo a;";
    autoFocusHandler = new Handler();
    mCamera = getCameraInstance();

    /* Instance barcode scanner */
    scanner = new ImageScanner();
    scanner.setConfig(0, Config.X_DENSITY, 3);
    scanner.setConfig(0, Config.Y_DENSITY, 3);

    Log.i(TAG, "CameraActivity onCreate()");
    mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
    FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
    preview.addView(mPreview);

    mCamera.setPreviewCallback(previewCb);
    mCamera.startPreview();
    previewing = true;
    mCamera.autoFocus(autoFocusCB);

    // 初始化声音和震动
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    // 如果手机是震动模式就震动
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
      playBeep = false;
    }
    // 初始化声音
    initBeepSound();
    initLoginDataBase();
    // MyApp.showToast(CameraActivity.this, "hello");

    Button mButtonBack = (Button) findViewById(R.id.button_back);

    /*返回按钮*/
    mButtonBack.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("downloadfile", "");
            setResult(RESULT_OK, intent);
            finish();
          }
        });
  }
Ejemplo n.º 27
0
  private void startPreview() {
    if (mPausing || mMainActivity.isFinishing()) return;

    ensureCameraDevice();

    // If we're previewing already, stop the preview first (this will blank
    // the screen).
    if (mPreviewing) stopPreview();

    setPreviewDisplay(mSurfaceHolder);
    setCameraParameters();

    // mCameraDevice.setPreviewCallback(mPreviewCallback);
    mCameraDevice.setPreviewCallback(cb);

    try {
      Log.v(TAG, "startPreview");
      mCameraDevice.startPreview();
    } catch (Throwable ex) {
      closeCamera();
      throw new RuntimeException("startPreview failed", ex);
    }
    mPreviewing = true;
    mStatus = IDLE;
  }
 private void initCamera() {
   if (!isPreview) {
     camera = Camera.open();
   }
   if (camera != null && !isPreview) {
     streamIt = new StreamIt();
     try {
       Camera.Parameters parameters = camera.getParameters();
       parameters.setPreviewSize(screenWidth, screenHeight); // 设置预览照片的大小	
       parameters.setPreviewFpsRange(20, 30); // 每秒显示20~30帧	
       parameters.setPictureFormat(ImageFormat.NV21); // 设置图片格式	
       parameters.setPictureSize(screenWidth, screenHeight); // 设置照片的大小
       camera.setPreviewDisplay(surfaceHolder); // 通过SurfaceView显示取景画面
       camera.setPreviewCallback(streamIt); // 设置回调的类	
       camera.startPreview(); // 开始预览	
       camera.autoFocus(null); // 自动对焦
     } catch (Exception e) {
       e.printStackTrace();
     }
     isPreview = true;
     Thread postThread2 = new Thread(new postThread());
     postThread2.start();
     System.out.println("线程启动了@@@@@@@@@@@@@@@@@@@@@@@@@@");
   }
 }
Ejemplo n.º 29
0
        public void onPictureTaken(byte[] data, Camera arg1) {

          if (data != null) {
            PictureTaken = true;

            // Extract the bitmap from data
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            // Only select the region we want
            bitmap =
                ThumbnailUtils.extractThumbnail(
                    bitmap, bitmap.getWidth() / 9, bitmap.getHeight() / 3);

            // Rotate the bitmap
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            bitmap =
                Bitmap.createBitmap(
                    bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            // Convert it back to byte array data
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bmArray = stream.toByteArray(); // Get the underlying pixel bytes array
            image = bmArray;
            if (image != null) {
              Toast.makeText(getActivity(), "Photo Taken", Toast.LENGTH_SHORT).show();
            }
          }
          cameraObject.startPreview();
        }
Ejemplo n.º 30
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (mHolder.getSurface() == null) {
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try {
      mCamera.stopPreview();
    } catch (Exception e) {
      // ignore: tried to stop a non-existent preview
    }

    // set preview size and make any resize, rotate or
    // reformatting changes here

    // start preview with new settings
    try {
      Camera.Parameters parameters = mCamera.getParameters();
      setCameraDisplayOrientation(
          ((Activity) this.getContext()), Camera.CameraInfo.CAMERA_FACING_FRONT, mCamera);
      mCamera.setParameters(parameters);

      mCamera.setPreviewCallback(previewCallback);
      mCamera.setPreviewDisplay(mHolder);
      mCamera.startPreview();

    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }