示例#1
1
  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 {
      mCamera.setPreviewDisplay(mHolder);

      // reference former
      Camera.Parameters parameters = mCamera.getParameters();
      int capWidth = parameters.getPreviewSize().width;
      int capHeight = parameters.getPreviewSize().height;
      // android.graphics.imageformat
      int pixelformat = parameters.getPreviewFormat();
      PixelFormat pixelinfo = new PixelFormat();
      PixelFormat.getPixelFormatInfo(pixelformat, pixelinfo);
      int cameraIndex = 0;
      boolean frontFacing = false;

      Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
      Camera.getCameraInfo(cameraIndex, cameraInfo);
      if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        frontFacing = true;
      }
      // For the default NV21 format, bitsPerPixel = 12.
      int bufSize = capWidth * capHeight * pixelinfo.bitsPerPixel / 8;

      for (int i = 0; i < 5; i++) {
        mCamera.addCallbackBuffer(new byte[bufSize]);
      }

      mCamera.startPreview();

      nftSimpleActivity.nativeVideoInit(capWidth, capHeight, cameraIndex, frontFacing);
    } catch (Exception e) {
      Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
  }
示例#2
0
 public void onPreviewFrame(byte[] data, Camera camera) {
   Camera.Parameters parameters = camera.getParameters();
   width = parameters.getPreviewSize().width;
   height = parameters.getPreviewSize().height;
   yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
   looped += 1;
 }
示例#3
0
 // Constructor
 public AudioSynth(
     final Camera camera,
     AudioTrack redSynthesizer,
     AudioTrack greenSynthesizer,
     AudioTrack blueSynthesizer) {
   mFinished = false;
   mRGBData = null;
   mRedSynthesizer = redSynthesizer;
   mGreenSynthesizer = greenSynthesizer;
   mBlueSynthesizer = blueSynthesizer;
   redGeneratedSnd = new short[maxSamples];
   greenGeneratedSnd = new short[maxSamples];
   blueGeneratedSnd = new short[maxSamples];
   mRedHistogram = new int[256];
   mGreenHistogram = new int[256];
   mBlueHistogram = new int[256];
   mBinSquared = new double[256];
   for (int bin = 0; bin < 256; bin++) {
     mBinSquared[bin] = ((double) bin) * bin;
   }
   Camera.Parameters params = camera.getParameters();
   mImageWidth = params.getPreviewSize().width;
   mImageHeight = params.getPreviewSize().height;
   int yStride = (int) Math.ceil(mImageWidth / 16.0) * 16;
   int uvStride = (int) Math.ceil((yStride / 2) / 16.0) * 16;
   int ySize = yStride * mImageHeight;
   int uvSize = uvStride * mImageHeight / 2;
   final int size = ySize + uvSize * 2;
   mYUVBuffer = new byte[size];
   camera.addCallbackBuffer(mYUVBuffer);
   mRGBData = new int[mImageWidth * mImageHeight];
 }
        public void onPreviewFrame(byte[] data, Camera camera) {
          try {
            Camera.Parameters parameters = camera.getParameters();
            width = parameters.getPreviewSize().width;
            height = parameters.getPreviewSize().height;
            yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
            imageReady = true;
            looped += 1;
          } catch (Exception e) {

          }
        }
示例#5
0
  public synchronized void setupCamera(int width, int height) {
    if (mCamera != null) {
      Log.i(TAG, "Setup Camera - " + width + "x" + height);
      Camera.Parameters params = mCamera.getParameters();
      List<Camera.Size> sizes = params.getSupportedPreviewSizes();
      mFrameWidth = width;
      mFrameHeight = height;

      // selecting optimal camera preview size
      {
        int minDiff = Integer.MAX_VALUE;
        for (Camera.Size size : sizes) {
          if (Math.abs(size.height - height) < minDiff) {
            mFrameWidth = size.width;
            mFrameHeight = size.height;
            minDiff = Math.abs(size.height - height);
          }
        }
      }

      params.setPreviewSize(getFrameWidth(), getFrameHeight());

      List<String> FocusModes = params.getSupportedFocusModes();
      if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
      }

      mCamera.setParameters(params);

      /* Now allocate the buffer */
      params = mCamera.getParameters();
      int size = params.getPreviewSize().width * params.getPreviewSize().height;
      size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
      mBuffer = new byte[size];
      /* The buffer where the current frame will be copied */
      mFrame = new byte[size];
      mCamera.addCallbackBuffer(mBuffer);

      /* Notify that the preview is about to be started and deliver preview size */
      onPreviewStarted(params.getPreviewSize().width, params.getPreviewSize().height);

      try {
        setPreview();
      } catch (IOException e) {
        Log.e(TAG, "mCamera.setPreviewDisplay/setPreviewTexture fails: " + e);
      }

      /* Now we can start a preview */
      mCamera.startPreview();
    }
  }
示例#6
0
  @SuppressLint("NewApi") // CameraInfo
  @SuppressWarnings("deprecation") // setPreviewFrameRate
  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

    if (camera != null) {

      String camResolution =
          PreferenceManager.getDefaultSharedPreferences(getContext())
              .getString(
                  "pref_cameraResolution",
                  getResources().getString(R.string.pref_defaultValue_cameraResolution));
      String[] dims = camResolution.split("x", 2);
      Camera.Parameters parameters = camera.getParameters();
      parameters.setPreviewSize(Integer.parseInt(dims[0]), Integer.parseInt(dims[1]));
      parameters.setPreviewFrameRate(30);
      camera.setParameters(parameters);

      parameters = camera.getParameters();
      int capWidth = parameters.getPreviewSize().width;
      int capHeight = parameters.getPreviewSize().height;
      int pixelformat = parameters.getPreviewFormat(); // android.graphics.imageformat
      PixelFormat pixelinfo = new PixelFormat();
      PixelFormat.getPixelFormatInfo(pixelformat, pixelinfo);
      int cameraIndex = 0;
      boolean frontFacing = false;
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraIndex =
            Integer.parseInt(
                PreferenceManager.getDefaultSharedPreferences(getContext())
                    .getString("pref_cameraIndex", "0"));
        Camera.getCameraInfo(cameraIndex, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) frontFacing = true;
      }

      int bufSize =
          capWidth
              * capHeight
              * pixelinfo.bitsPerPixel
              / 8; // For the default NV21 format, bitsPerPixel = 12.

      for (int i = 0; i < 5; i++) camera.addCallbackBuffer(new byte[bufSize]);

      camera.startPreview();

      nftBookActivity.nativeVideoInit(capWidth, capHeight, cameraIndex, frontFacing);
    }
  }
  public void startCamera() {

    camera = openCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
    camera.setPreviewCallback(previewCallback);

    Camera.Parameters parameters = camera.getParameters();

    width = parameters.getPreviewSize().width / ds;
    height = parameters.getPreviewSize().height / ds;
    parameters.setPreviewSize(width, height);

    camera.setParameters(parameters);

    data = parameters.flatten();
  }
        public void onPreviewFrame(byte[] data, Camera camera) {
          Camera.Parameters parameters = camera.getParameters();
          Size size = parameters.getPreviewSize();

          Image barcode = new Image(size.width, size.height, "Y800");
          barcode.setData(data);

          int result = scanner.scanImage(barcode);

          String strScanResult = "";

          if (result != 0) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();

            SymbolSet syms = scanner.getResults();
            for (Symbol sym : syms) {
              // scanText.setText("barcode result " + sym.getData());
              strScanResult += sym.getData();
              barcodeScanned = true;
            }

            Intent myIntent = new Intent(MainActivity.this, ValidateBarCodeResult.class);
            myIntent.putExtra("barcode_result", strScanResult);
            startActivity(myIntent);
          }
        }
  @Override
  public void onPreviewFrame(byte[] data, Camera camera) {
    Camera.Parameters params = camera.getParameters();
    int w = params.getPreviewSize().width;
    int h = params.getPreviewSize().height;
    int format = params.getPreviewFormat();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    YuvImage image = new YuvImage(data, format, w, h, null);
    Rect area = new Rect(0, 0, w, h);

    long start = System.currentTimeMillis();
    image.compressToJpeg(area, imageQuality, out);
    long end = System.currentTimeMillis();

    long pingTime = ServerConnector.getInstance().getPingTime() + (end - start);
    if (pingTime > 50 && imageQuality > 25) {
      imageQuality--;
    } else if (pingTime < 50 && imageQuality < 100) {
      imageQuality++;
    }

    Log.i("image", "" + imageQuality);

    ServerConnector.getInstance().pushImage(out.toByteArray());
  }
  private void setPreviewCallback() {
    if (mCamera == null) {
      android.util.Log.e("MOSYNC INTERNAL", "No Preview set");
      return;
    }

    try {
      // We have to use and static instance of the camera in the reflection here
      mSetPreviewCallbackWithBuffer =
          mCamera
              .getClass()
              .getMethod("setPreviewCallbackWithBuffer", Camera.PreviewCallback.class);

      Camera.Parameters parameters = getCurrentParameters();
      Camera.Size size = parameters.getPreviewSize();

      mCallbackBuffer = new byte[size.width * size.height * 4];

      mCamera.addCallbackBuffer(mCallbackBuffer);

      mIsUsingPreviewCallbackBuffer = true;

      mCamera.setPreviewCallbackWithBuffer(previewCallback);

    } catch (NoSuchMethodException nsme) {
      mIsUsingPreviewCallbackBuffer = false;

      mCamera.setPreviewCallback(previewCallback);
    }
  }
  public void onPreviewFrame(byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    Camera.Size size = parameters.getPreviewSize();

    Image barcode = new Image(size.width, size.height, "Y800");
    barcode.setData(data);

    int result = mScanner.scanImage(barcode);

    if (result != 0) {
      mCamera.cancelAutoFocus();
      mCamera.setPreviewCallback(null);
      mCamera.stopPreview();
      mPreviewing = false;
      SymbolSet syms = mScanner.getResults();
      for (Symbol sym : syms) {
        String symData = sym.getData();
        if (!TextUtils.isEmpty(symData)) {
          Intent dataIntent = new Intent();
          dataIntent.putExtra(SCAN_RESULT, symData);
          dataIntent.putExtra(SCAN_RESULT_TYPE, sym.getType());
          setResult(Activity.RESULT_OK, dataIntent);
          finish();
          break;
        }
      }
    }
  }
    @SuppressWarnings("ConstantConditions")
    public void onPreviewFrame(byte[] data, Camera incomingCamera) {
      try {
        if (System.currentTimeMillis() > lastSnapshotTime) {
          lastSnapshotTime = System.currentTimeMillis() + SNAPSHOT_DELAY;

          Camera.Parameters cameraParameters = incomingCamera.getParameters();
          Camera.Size previewSize = cameraParameters.getPreviewSize();
          Image barcode = new Image(previewSize.width, previewSize.height, GREY_COLOR_SPACE);
          barcode.setData(data);

          if (scanner.scanImage(barcode) != 0) {
            SymbolSet scannerResults = scanner.getResults();

            if (vibrator != null) vibrator.vibrate(VIBRATE_TIME);

            for (Symbol symbol : scannerResults)
              if (scannerListener == null)
                Toast.makeText(getActivity(), symbol.getData(), Toast.LENGTH_LONG).show();
              else scannerListener.onDataReceive(symbol.getData(), symbol.getType());
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  void setDesiredCameraParameters(OpenCamera camera, boolean safeMode) {

    Camera theCamera = camera.getCamera();
    Camera.Parameters parameters = theCamera.getParameters();

    //    theCamera.setDisplayOrientation(90);//add 这句代码作用是旋转镜头90度,使相机预览方向正确显示

    if (parameters == null) {
      Log.w(
          TAG,
          "Device error: no camera parameters are available. Proceeding without configuration.");
      return;
    }

    Log.i(TAG, "Initial camera parameters: " + parameters.flatten());

    if (safeMode) {
      Log.w(TAG, "In camera config safe mode -- most settings will not be honored");
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    initializeTorch(parameters, prefs, safeMode);

    CameraConfigurationUtils.setFocus(parameters, true, true, safeMode);

    if (!safeMode) {
      CameraConfigurationUtils.setBarcodeSceneMode(parameters);
      CameraConfigurationUtils.setVideoStabilization(parameters);
      CameraConfigurationUtils.setFocusArea(parameters);
      CameraConfigurationUtils.setMetering(parameters);
    }

    parameters.setPreviewSize(bestPreviewSize.x, bestPreviewSize.y);

    theCamera.setParameters(parameters);

    theCamera.setDisplayOrientation(cwRotationFromDisplayToCamera);

    Camera.Parameters afterParameters = theCamera.getParameters();
    Camera.Size afterSize = afterParameters.getPreviewSize();
    if (afterSize != null
        && (bestPreviewSize.x != afterSize.width || bestPreviewSize.y != afterSize.height)) {
      Log.w(
          TAG,
          "Camera said it supported preview size "
              + bestPreviewSize.x
              + 'x'
              + bestPreviewSize.y
              + ", but after setting it, preview size is "
              + afterSize.width
              + 'x'
              + afterSize.height);
      bestPreviewSize.x = afterSize.width;
      bestPreviewSize.y = afterSize.height;
    }
  }
示例#14
0
  public static Mat[] getMatArray(byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    int width = parameters.getPreviewSize().width;
    int height = parameters.getPreviewSize().height;

    Mat yuv = new Mat(height + height / 2, width, CvType.CV_8UC1);
    Mat rgba = new Mat(height, width, CvType.CV_8UC1);
    yuv.put(0, 0, data);
    Imgproc.cvtColor(yuv, rgba, Imgproc.COLOR_YUV2RGB_NV21);

    Mat rgbaResult = rotateMat(rgba);
    Mat grayResult = new Mat(rgbaResult.height(), rgbaResult.width(), CvType.CV_8UC1);
    Imgproc.cvtColor(rgbaResult, grayResult, Imgproc.COLOR_BGR2GRAY);

    yuv.release();
    rgba.release();
    Mat[] result = {grayResult, rgbaResult};
    return result;
  }
示例#15
0
  public static Point findBestPreviewSizeValue(
      Camera.Parameters parameters, Point screenResolution) {

    List<Camera.Size> supportedPreviewSizes =
        new ArrayList<Camera.Size>(parameters.getSupportedPreviewSizes());

    Collections.sort(
        supportedPreviewSizes,
        new Comparator<Camera.Size>() {
          @Override
          public int compare(Camera.Size a, Camera.Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels < aPixels) {
              return -1;
            }
            if (bPixels > aPixels) {
              return 1;
            }
            return 0;
          }
        });

    Point bestSize = null;
    float screenAspectRatio = (float) screenResolution.x / (float) screenResolution.y;

    float diff = Float.POSITIVE_INFINITY;
    for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
      int realWidth = supportedPreviewSize.width;
      int realHeight = supportedPreviewSize.height;
      int pixels = realWidth * realHeight;
      if (pixels < MIN_PREVIEW_PIXELS || pixels > MAX_PREVIEW_PIXELS) {
        continue;
      }
      boolean isCandidatePortrait = realWidth < realHeight;
      int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
      int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
      if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
        return new Point(realWidth, realHeight);
      }
      float aspectRatio = (float) maybeFlippedWidth / (float) maybeFlippedHeight;
      float newDiff = Math.abs(aspectRatio - screenAspectRatio);
      if (newDiff < diff) {
        bestSize = new Point(realWidth, realHeight);
        diff = newDiff;
      }
    }

    if (bestSize == null) {
      Camera.Size defaultSize = parameters.getPreviewSize();
      bestSize = new Point(defaultSize.width, defaultSize.height);
    }
    return bestSize;
  }
  /**
   * Opens a camera, and attempts to establish preview mode at the specified width and height.
   *
   * <p>Sets mCameraPreviewWidth and mCameraPreviewHeight to the actual width/height of the preview.
   */
  private void openCamera(int desiredWidth, int desiredHeight) {
    if (mCamera != null) {
      throw new RuntimeException("camera already initialized");
    }

    Camera.CameraInfo info = new Camera.CameraInfo();

    // Try to find a back-facing camera (e.g. for videoconferencing).
    int numCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numCameras; i++) {
      Camera.getCameraInfo(i, info);
      //            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {  //TODO: front
      // facing
      if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
        mCamera = Camera.open(i);
        break;
      }
    }
    if (mCamera == null) {
      Log.d(TAG, "No front-facing camera found; opening default");
      mCamera = Camera.open(); // opens first back-facing camera
    }
    if (mCamera == null) {
      throw new RuntimeException("Unable to open camera");
    }
    mCamera.setDisplayOrientation(90); // TODO: set according to front or back facing

    Camera.Parameters parms = mCamera.getParameters();
    //        parms.setRotation(180);

    CameraUtils.choosePreviewSize(parms, desiredWidth, desiredHeight);

    // Give the camera a hint that we're recording video.  This can have a big
    // impact on frame rate.
    parms.setRecordingHint(true);

    // leave the frame rate set to default
    mCamera.setParameters(parms);

    int[] fpsRange = new int[2];
    Camera.Size mCameraPreviewSize = parms.getPreviewSize();
    parms.getPreviewFpsRange(fpsRange);
    String previewFacts = mCameraPreviewSize.width + "x" + mCameraPreviewSize.height;
    if (fpsRange[0] == fpsRange[1]) {
      previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps";
    } else {
      previewFacts += " @[" + (fpsRange[0] / 1000.0) + " - " + (fpsRange[1] / 1000.0) + "] fps";
    }
    TextView text = (TextView) findViewById(R.id.cameraParams_text);
    text.setText(previewFacts);

    mCameraPreviewWidth = mCameraPreviewSize.width;
    mCameraPreviewHeight = mCameraPreviewSize.height;
  }
  private static Camera.Size findBestPreviewSizeValue(
      final Camera.Parameters parameters, Rect surfaceResolution) {
    if (surfaceResolution.height() > surfaceResolution.width())
      surfaceResolution = new Rect(0, 0, surfaceResolution.height(), surfaceResolution.width());

    final float screenAspectRatio =
        (float) surfaceResolution.width() / (float) surfaceResolution.height();

    final List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
    if (rawSupportedSizes == null) return parameters.getPreviewSize();

    // sort by size, descending
    final List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(rawSupportedSizes);
    Collections.sort(supportedPreviewSizes, numPixelComparator);

    Camera.Size bestSize = null;
    float diff = Float.POSITIVE_INFINITY;

    for (final Camera.Size supportedPreviewSize : supportedPreviewSizes) {
      final int realWidth = supportedPreviewSize.width;
      final int realHeight = supportedPreviewSize.height;
      final int realPixels = realWidth * realHeight;
      if (realPixels < MIN_PREVIEW_PIXELS || realPixels > MAX_PREVIEW_PIXELS) continue;

      final boolean isCandidatePortrait = realWidth < realHeight;
      final int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
      final int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
      if (maybeFlippedWidth == surfaceResolution.width()
          && maybeFlippedHeight == surfaceResolution.height()) return supportedPreviewSize;

      final float aspectRatio = (float) maybeFlippedWidth / (float) maybeFlippedHeight;
      final float newDiff = Math.abs(aspectRatio - screenAspectRatio);
      if (newDiff < diff) {
        bestSize = supportedPreviewSize;
        diff = newDiff;
      }
    }

    if (bestSize != null) return bestSize;
    else return parameters.getPreviewSize();
  }
  public int getPreviewSize() {
    acquireCamera();

    Camera.Parameters parameters = getCurrentParameters();
    Camera.Size size = parameters.getPreviewSize();

    int width = ((size.width & 0x0000ffff) << 16);
    int height = (size.height & 0x0000ffff);
    int extent = EXTENT(size.width, size.height);

    return extent;
  }
 @Override
 public void onPreviewFrame(byte[] data, Camera camera) {
   Camera.Parameters parameters = camera.getParameters();
   Camera.Size size = parameters.getPreviewSize();
   int width = size.width;
   int height = size.height;
   barcodeScanner.scanImage(
       data,
       width,
       height,
       new Scan.ResultCallback() {
         @Override
         public void onDecodeBarcode(Result result) {
           onBarcodeScanned(result);
         }
       });
 }
示例#20
0
  /**
   * Opens a camera, and attempts to establish preview mode at the specified width and height.
   *
   * <p>Sets mCameraPreviewWidth and mCameraPreviewHeight to the actual width/height of the preview.
   */
  private void openCamera(int desiredWidth, int desiredHeight) {
    if (mCamera != null) {
      throw new RuntimeException("camera already initialized");
    }

    Camera.CameraInfo info = new Camera.CameraInfo();

    // Try to find a front-facing camera (e.g. for videoconferencing).
    int numCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numCameras; i++) {
      Camera.getCameraInfo(i, info);
      if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        mCamera = Camera.open(i);
        break;
      }
    }
    if (mCamera == null) {
      Log.d(TAG, "No front-facing camera found; opening default");
      mCamera = Camera.open(); // opens first back-facing camera
    }
    if (mCamera == null) {
      throw new RuntimeException("Unable to open camera");
    }

    Camera.Parameters parms = mCamera.getParameters();

    choosePreviewSize(parms, desiredWidth, desiredHeight);
    // leave the frame rate set to default
    mCamera.setParameters(parms);

    int[] fpsRange = new int[2];
    Camera.Size mCameraPreviewSize = parms.getPreviewSize();
    parms.getPreviewFpsRange(fpsRange);
    String previewFacts = mCameraPreviewSize.width + "x" + mCameraPreviewSize.height;
    if (fpsRange[0] == fpsRange[1]) {
      previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps";
    } else {
      previewFacts += " @[" + (fpsRange[0] / 1000.0) + " - " + (fpsRange[1] / 1000.0) + "] fps";
    }
    TextView text = (TextView) findViewById(R.id.cameraParams_text);
    text.setText(previewFacts);

    mCameraPreviewWidth = mCameraPreviewSize.width;
    mCameraPreviewHeight = mCameraPreviewSize.height;
  }
  /*
  Sets the camera up to take preview images which are used for both preview and decoding
    */
  private void setCameraParameters() {
    Camera.Parameters parameters = camera.getParameters();
    Camera.Size size = parameters.getPreviewSize();
    Log.v(TAG, "Default preview size: " + size.width + ", " + size.height);
    previewFormat = parameters.getPreviewFormat();
    previewFormatString = parameters.get("preview-format");
    Log.v(TAG, "Default preview format: " + previewFormat);

    // Ensure that the camera resolution is a multiple of 8, as the screen may not be.
    cameraResolution = new Point();
    cameraResolution.x = (screenResolution.x >> 3) << 3;
    cameraResolution.y = (screenResolution.y >> 3) << 3;
    Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    parameters.set("flash-value", 2);
    parameters.set("flash-mode", "off");
    camera.setParameters(parameters);
  }
  /**
   * Sets the MoSyncCameraPreview object to be controlled
   *
   * @param preview an object of MoSyncCameraPreview that has already been initialized
   */
  public void setPreview(MoSyncCameraPreview preview) {

    acquireCamera();

    mPreview = preview;
    if (mPreview.mCamera == null) {
      mPreview.mCamera = mCamera;
      mPreview.initiateCamera();
      mPreview.mCameraIndex = mCurrentCameraIndex;

      setPreviewCallback();

      Camera.Parameters parameters = getCurrentParameters();
      Camera.Size size = parameters.getPreviewSize();

      mImageBuffer = new byte[size.width * size.height * 4];
    }
  }
  void setDesiredCameraParameters(Camera camera, boolean safeMode) {
    Camera.Parameters parameters = camera.getParameters();
    if (parameters == null) {
      Log.w(
          TAG,
          "Device error: no camera parameters are available. Proceeding without configuration.");
      return;
    }

    initializeTorch(parameters, safeMode);

    CameraConfigurationUtils.setFocus(parameters, true, true, safeMode);

    if (!safeMode) {
      CameraConfigurationUtils.setBarcodeSceneMode(parameters);
      CameraConfigurationUtils.setVideoStabilization(parameters);
      CameraConfigurationUtils.setFocusArea(parameters);
      CameraConfigurationUtils.setMetering(parameters);
    }

    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    Log.i(TAG, "Final camera parameters: " + parameters.flatten());

    camera.setParameters(parameters);
    Camera.Parameters afterParameters = camera.getParameters();
    Camera.Size afterSize = afterParameters.getPreviewSize();
    if (afterSize != null
        && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) {
      Log.w(
          TAG,
          "Camera said it supported preview size "
              + cameraResolution.x
              + 'x'
              + cameraResolution.y
              + ", but after setting it, preview size is "
              + afterSize.width
              + 'x'
              + afterSize.height);
      cameraResolution.x = afterSize.width;
      cameraResolution.y = afterSize.height;
    }

    camera.setDisplayOrientation(90);
  }
示例#24
0
        public void onPreviewFrame(byte[] data, Camera camera) {
          Camera.Parameters parameters = camera.getParameters();
          Camera.Size size = parameters.getPreviewSize();

          Image barcode = new Image(size.width, size.height, "Y800");
          barcode.setData(data);

          int result = scanner.scanImage(barcode);

          if (result != 0) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();

            SymbolSet syms = scanner.getResults();

            playBeepSoundAndVibrate(); // 播放声音和振动代表成功获取二维码

            for (Symbol sym : syms) {
              // 将扫描后的信息返回
              String resultStr = sym.getData();
              Log.i(TAG, "resultStr: " + resultStr);
              if (resultStr.isEmpty() || !resultStr.substring(0, 7).equalsIgnoreCase("http://")) {
                // Message msg = new Message();
                // msg.what = MSG_SCANRESULT_NONE;
                // myHandler.sendMessage(msg);
                MyApp.showToast(mContext, "二维码信息内容不符合房产投票项目的要求, 请联系管理人员!");
                Intent intent = new Intent();
                intent.putExtra("downloadfile", "");
                setResult(RESULT_OK, intent);
                finish();
              } else {
                downLoadDBFile(resultStr);
                //      mLoginSqldb.close();
                //       mVoteSqldb.close();
                Intent intent = new Intent();
                intent.putExtra("downloadfile", mDownloadfile);
                setResult(RESULT_OK, intent);
                finish();
              }
            }
          }
        }
示例#25
0
文件: MarvinEye.java 项目: ghk/Marvin
  @Override
  public void surfaceCreated(SurfaceHolder arg0) {
    camera = Camera.open();
    Camera.Parameters params = camera.getParameters();
    camera.setDisplayOrientation(90);
    params.setRotation(90);
    params.set("orientation", "landscape");
    params.set("rotation", 90);
    params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    Camera.Size previewSize = params.getPreviewSize();
    List<Camera.Size> previewSizes = params.getSupportedPreviewSizes();
    int i = 0;
    for (Camera.Size cs : previewSizes) {
      Log.d(MarvinActivity.TAG, "Camera - supports:(" + (i++) + ") " + cs.width + "x" + cs.height);
    }

    previewSize.width = 720;
    previewSize.height = 480;

    params.setSceneMode("portrait");
    Log.d(MarvinActivity.TAG, "w: " + previewSize.width + " h: " + previewSize.height);
    List<Integer> formats = params.getSupportedPreviewFormats();
    for (Integer format : formats) {
      Log.d(MarvinActivity.TAG, "Camera - supports preview format: " + format);
    }
    params.setPreviewSize(previewSize.width, previewSize.height);
    camera.setParameters(params);

    detectThread = new FaceDetectThread(context, user, params);
    detectThread.start();
    camera.setPreviewCallback(detectThread);
    try {
      camera.setPreviewDisplay(cameraView.getHolder());
      camera.startPreview();
      Log.d(MarvinActivity.TAG, "preview started");
    } catch (Exception e) {
      Log.e(MarvinActivity.TAG, e.getMessage(), e);
    }
    user.onEyeStarted();
  }
        public void onPreviewFrame(byte[] data, Camera camera) {
          Camera.Parameters parameters = camera.getParameters();
          Size size = parameters.getPreviewSize();

          Image barcode = new Image(size.width, size.height, "Y800");
          barcode.setData(data);

          int result = scanner.scanImage(barcode);

          if (result != 0) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            //  mCamera.stopPreview();

            SymbolSet syms = scanner.getResults();
            for (Symbol sym : syms) {
              scanText.setText("barcode" + sym.getData());

              barcodeScanned = true;
              launchIntent(syms);
            }
          }
        }
示例#27
0
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = mCamera.getParameters();

    List<Size> sizes = parameters.getSupportedPreviewSizes();
    Size optimalSize = getOptimalPreviewSize(sizes, w, h);
    parameters.setPreviewSize(optimalSize.width, optimalSize.height);

    mCamera.setParameters(parameters);
    if (previewCallback != null) {
      mCamera.setPreviewCallbackWithBuffer(previewCallback);
      Camera.Size size = parameters.getPreviewSize();
      byte[] data =
          new byte
              [size.width
                  * size.height
                  * ImageFormat.getBitsPerPixel(parameters.getPreviewFormat())
                  / 8];
      mCamera.addCallbackBuffer(data);
    }
    mCamera.startPreview();
  }
  public static Point findBestPreviewSizeValue(
      Camera.Parameters parameters, Point screenResolution) {

    List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
    if (rawSupportedSizes == null) {
      Log.w(TAG, "Device returned no supported preview sizes; using default");
      Camera.Size defaultSize = parameters.getPreviewSize();
      if (defaultSize == null) {
        throw new IllegalStateException("Parameters contained no preview size!");
      }
      return new Point(defaultSize.width, defaultSize.height);
    }

    // Sort by size, descending
    List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(rawSupportedSizes);
    Collections.sort(
        supportedPreviewSizes,
        new Comparator<Camera.Size>() {
          @Override
          public int compare(Camera.Size a, Camera.Size b) {
            int aPixels = a.height * a.width;
            int bPixels = b.height * b.width;
            if (bPixels < aPixels) {
              return -1;
            }
            if (bPixels > aPixels) {
              return 1;
            }
            return 0;
          }
        });

    if (Log.isLoggable(TAG, Log.INFO)) {
      StringBuilder previewSizesString = new StringBuilder();
      for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
        previewSizesString
            .append(supportedPreviewSize.width)
            .append('x')
            .append(supportedPreviewSize.height)
            .append(' ');
      }
      Log.i(TAG, "Supported preview sizes: " + previewSizesString);
    }

    double screenAspectRatio = 0d;
    if (ZXingConfigManager.getInstance().isPortrait()) {
      // 这里调换Y和X 不然竖屏部分机型会拉伸
      screenAspectRatio = (double) screenResolution.y / (double) screenResolution.x;
    } else {
      screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;
    }

    // Remove sizes that are unsuitable
    Iterator<Camera.Size> it = supportedPreviewSizes.iterator();
    while (it.hasNext()) {
      Camera.Size supportedPreviewSize = it.next();
      int realWidth = supportedPreviewSize.width;
      int realHeight = supportedPreviewSize.height;
      if (realWidth * realHeight < MIN_PREVIEW_PIXELS) {
        it.remove();
        continue;
      }

      boolean isCandidatePortrait = realWidth < realHeight;
      int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;
      int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;
      double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight;
      double distortion = Math.abs(aspectRatio - screenAspectRatio);
      if (distortion > MAX_ASPECT_DISTORTION) {
        it.remove();
        continue;
      }

      if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) {
        Point exactPoint = new Point(realWidth, realHeight);
        Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint);
        return exactPoint;
      }
    }

    // If no exact match, use largest preview size. This was not a great
    // idea on older devices because
    // of the additional computation needed. We're likely to get here on
    // newer Android 4+ devices, where
    // the CPU is much more powerful.
    if (!supportedPreviewSizes.isEmpty()) {
      Camera.Size largestPreview = supportedPreviewSizes.get(0);
      Point largestSize = new Point(largestPreview.width, largestPreview.height);
      Log.i(TAG, "Using largest suitable preview size: " + largestSize);
      return largestSize;
    }

    // If there is nothing at all suitable, return current preview size
    Camera.Size defaultPreview = parameters.getPreviewSize();
    if (defaultPreview == null) {
      throw new IllegalStateException("Parameters contained no preview size!");
    }
    Point defaultSize = new Point(defaultPreview.width, defaultPreview.height);
    Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize);
    return defaultSize;
  }
示例#29
0
  @TargetApi(11)
  protected boolean initializeCamera(int width, int height) {
    Log.d(TAG, "Initialize java camera");
    boolean result = true;
    synchronized (this) {
      mCamera = null;

      if (mCameraIndex == -1) {
        Log.d(TAG, "Trying to open camera with old open()");
        try {
          mCamera = Camera.open();
        } catch (Exception e) {
          Log.e(
              TAG,
              "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
        }

        if (mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          boolean connected = false;
          for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
            Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
            try {
              mCamera = Camera.open(camIdx);
              connected = true;
            } catch (RuntimeException e) {
              Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
            }
            if (connected) break;
          }
        }
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(mCameraIndex) + ")");
          try {
            mCamera = Camera.open(mCameraIndex);
          } catch (RuntimeException e) {
            Log.e(TAG, "Camera #" + mCameraIndex + "failed to open: " + e.getLocalizedMessage());
          }
        }
      }

      if (mCamera == null) return false;

      /* Now set camera parameters */
      try {
        Camera.Parameters params = mCamera.getParameters();
        Log.d(TAG, "getSupportedPreviewSizes()");
        List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();

        if (sizes != null) {
          /* Select the size that fits surface considering maximum size allowed */
          Size frameSize =
              calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height);

          params.setPreviewFormat(ImageFormat.NV21);
          Log.d(
              TAG,
              "Set preview size to "
                  + Integer.valueOf((int) frameSize.width)
                  + "x"
                  + Integer.valueOf((int) frameSize.height));
          params.setPreviewSize((int) frameSize.width, (int) frameSize.height);

          List<String> FocusModes = params.getSupportedFocusModes();
          if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
          }

          mCamera.setParameters(params);
          params = mCamera.getParameters();

          mFrameWidth = params.getPreviewSize().width;
          mFrameHeight = params.getPreviewSize().height;

          if (mFpsMeter != null) {
            mFpsMeter.setResolution(mFrameWidth, mFrameHeight);
          }

          int size = mFrameWidth * mFrameHeight;
          size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
          mBuffer = new byte[size];

          mCamera.addCallbackBuffer(mBuffer);
          mCamera.setPreviewCallbackWithBuffer(this);

          mBaseMat = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);

          mFrameChain = new Mat[2];
          mFrameChain[0] = new Mat();
          mFrameChain[1] = new Mat();

          AllocateCache();

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
            getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            mCamera.setPreviewTexture(mSurfaceTexture);
          } else mCamera.setPreviewDisplay(null);

          /* Finally we are ready to start the preview */
          Log.d(TAG, "startPreview");
          mCamera.startPreview();
        } else result = false;
      } catch (Exception e) {
        result = false;
        e.printStackTrace();
      }
    }

    return result;
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    if (camera != null) {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);

      if (cameraRotation == 90 || cameraRotation == 270) {
        int aux = widthMode;
        widthMode = heightMode;
        heightMode = aux;
        aux = widthSize;
        widthSize = heightSize;
        heightSize = aux;
      }

      Size previewSize = null;
      if (widthMode == MeasureSpec.UNSPECIFIED && heightMode == MeasureSpec.UNSPECIFIED) {
        previewSize = previewSizes.get(0); // Choose the biggest preview size
        layoutWidth = previewSize.width;
        layoutHeight = previewSize.height;
      } else if (widthMode == MeasureSpec.UNSPECIFIED) { // heigthMode == EXACTLY or AT_MOST
        previewSize = bestSizeForHeight(previewSizes, heightSize);
        layoutWidth = previewSize.width * heightSize / previewSize.height;
        layoutHeight = heightSize;
      } else if (heightMode == MeasureSpec.UNSPECIFIED) { // widthMode == EXACTLY or AT_MOST
        previewSize = bestSizeForWidth(previewSizes, widthSize);
        layoutWidth = widthSize;
        layoutHeight = previewSize.height * widthSize / previewSize.width;
      } else if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
        if (widthSize * pictureSize.height > heightSize * pictureSize.width)
          previewSize = bestSizeForWidth(previewSizes, widthSize);
        else previewSize = bestSizeForHeight(previewSizes, heightSize);
        layoutWidth = widthSize;
        layoutHeight = heightSize;
      } else if (widthMode == MeasureSpec.EXACTLY) { // heigthMode == AT_MOST
        previewSize = bestSizeForWidth(previewSizes, widthSize);
        layoutWidth = widthSize;
        if (widthSize * pictureSize.height > heightSize * pictureSize.width)
          layoutHeight = heightSize;
        else layoutHeight = pictureSize.height * widthSize / pictureSize.width;
      } else if (heightMode == MeasureSpec.EXACTLY) { // widthMode == AT_MOST
        previewSize = bestSizeForHeight(previewSizes, heightSize);
        if (widthSize * pictureSize.height > heightSize * pictureSize.width)
          layoutWidth = pictureSize.width * heightSize / pictureSize.height;
        else layoutWidth = widthSize;
        layoutHeight = heightSize;
      } else { // widthMode == heightMode == AT_MOST
        if (widthSize * pictureSize.height > heightSize * pictureSize.width) {
          previewSize = bestSizeForHeight(previewSizes, heightSize);
          layoutWidth = pictureSize.width * heightSize / pictureSize.height;
          layoutHeight = heightSize;
        } else {
          previewSize = bestSizeForWidth(previewSizes, widthSize);
          layoutWidth = widthSize;
          layoutHeight = pictureSize.height * widthSize / pictureSize.width;
        }
      }

      if (cameraRotation == 90 || cameraRotation == 270) {
        final int aux = layoutWidth;
        layoutWidth = layoutHeight;
        layoutHeight = aux;
      }

      // TODO Review this...
      final Camera.Parameters params = camera.getParameters();
      if (!previewSize.equals(params.getPreviewSize())) {
        camera.stopPreview();
        params.setPreviewSize(previewSize.width, previewSize.height);
        camera.setParameters(params);
        camera.startPreview();
      }

      cropOverlayBitmapRect.left = 0;
      cropOverlayBitmapRect.top = 0;
      cropOverlayBitmapRect.right = layoutWidth;
      cropOverlayBitmapRect.bottom = layoutHeight;
      cropOverlayView.setBitmapRect(cropOverlayBitmapRect);

      setMeasuredDimension(layoutWidth, layoutHeight);

    } else {
      setMeasuredDimension(widthSize, heightSize);
    }
  }