Java Code Examples for android.hardware.Camera#setParameters()

The following examples show how to use android.hardware.Camera#setParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Camera1Manager.java    From sandriosCamera with MIT License 6 votes vote down vote up
private void setCameraPhotoQuality(Camera camera) {
    Camera.Parameters parameters = camera.getParameters();

    parameters.setPictureFormat(PixelFormat.JPEG);

    if (configurationProvider.getMediaQuality() == CameraConfiguration.MEDIA_QUALITY_LOW) {
        parameters.setJpegQuality(50);
    } else if (configurationProvider.getMediaQuality() == CameraConfiguration.MEDIA_QUALITY_MEDIUM) {
        parameters.setJpegQuality(75);
    } else if (configurationProvider.getMediaQuality() == CameraConfiguration.MEDIA_QUALITY_HIGH) {
        parameters.setJpegQuality(100);
    } else if (configurationProvider.getMediaQuality() == CameraConfiguration.MEDIA_QUALITY_HIGHEST) {
        parameters.setJpegQuality(100);
    }
    parameters.setPictureSize(photoSize.getWidth(), photoSize.getHeight());

    camera.setParameters(parameters);
}
 
Example 2
Source File: CameraManager.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private static void setTorchEnabled(final Camera camera, final boolean enabled) {
    final Camera.Parameters parameters = camera.getParameters();

    final List<String> supportedFlashModes = parameters.getSupportedFlashModes();
    if (supportedFlashModes != null) {
        final String flashMode;
        if (enabled)
            flashMode = findValue(supportedFlashModes, Camera.Parameters.FLASH_MODE_TORCH,
                    Camera.Parameters.FLASH_MODE_ON);
        else
            flashMode = findValue(supportedFlashModes, Camera.Parameters.FLASH_MODE_OFF);

        if (flashMode != null) {
            camera.cancelAutoFocus(); // autofocus can cause conflict

            parameters.setFlashMode(flashMode);
            camera.setParameters(parameters);
        }
    }
}
 
Example 3
Source File: Camera1Manager.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private void setCameraPhotoQuality(Camera camera) {
    final Camera.Parameters parameters = camera.getParameters();

    parameters.setPictureFormat(PixelFormat.JPEG);

    if (configurationProvider.getMediaQuality() == Configuration.MEDIA_QUALITY_LOW) {
        parameters.setJpegQuality(50);
    } else if (configurationProvider.getMediaQuality() == Configuration.MEDIA_QUALITY_MEDIUM) {
        parameters.setJpegQuality(75);
    } else if (configurationProvider.getMediaQuality() == Configuration.MEDIA_QUALITY_HIGH) {
        parameters.setJpegQuality(100);
    } else if (configurationProvider.getMediaQuality() == Configuration.MEDIA_QUALITY_HIGHEST) {
        parameters.setJpegQuality(100);
    }
    parameters.setPictureSize(photoSize.getWidth(), photoSize.getHeight());

    camera.setParameters(parameters);
}
 
Example 4
Source File: CameraManager.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private static void setTorchEnabled(final Camera camera, final boolean enabled) {
    final Camera.Parameters parameters = camera.getParameters();

    final List<String> supportedFlashModes = parameters.getSupportedFlashModes();
    if (supportedFlashModes != null) {
        final String flashMode;
        if (enabled)
            flashMode = findValue(supportedFlashModes, Camera.Parameters.FLASH_MODE_TORCH,
                    Camera.Parameters.FLASH_MODE_ON);
        else
            flashMode = findValue(supportedFlashModes, Camera.Parameters.FLASH_MODE_OFF);

        if (flashMode != null) {
            camera.cancelAutoFocus(); // autofocus can cause conflict

            parameters.setFlashMode(flashMode);
            camera.setParameters(parameters);
        }
    }
}
 
Example 5
Source File: CameraUtil.java    From TextOcrExample with Apache License 2.0 6 votes vote down vote up
/**
 * 打开闪关灯
 */
public void turnLightOn(Camera mCamera) {
    if (mCamera == null) {
        return;
    }
    Camera.Parameters parameters = mCamera.getParameters();
    if (parameters == null) {
        return;
    }
    List<String> flashModes = parameters.getSupportedFlashModes();
    // Check if camera flash exists
    if (flashModes == null) {
        // Use the screen as a flashlight (next best thing)
        return;
    }
    String flashMode = parameters.getFlashMode();
    if (!Camera.Parameters.FLASH_MODE_ON.equals(flashMode)) {
        // Turn on the flash
        if (flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            mCamera.setParameters(parameters);
        } else {
        }
    }
}
 
Example 6
Source File: CameraConfigurationManager.java    From Roid-Library with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the camera up to take preview images which are used for both
 * preview and decoding. We detect the preview format here so that
 * buildLuminanceSource() can build an appropriate LuminanceSource
 * subclass. In the future we may want to force YUV420SP as it's the
 * smallest, and the planar Y can be used for barcode scanning without a
 * copy in some cases.
 */
void setDesiredCameraParameters(Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    Log.d(TAG, "Setting preview size: " + cameraResolution);
    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    setFlash(parameters);
    setZoom(parameters);
    // setSharpness(parameters);
    // modify here
    camera.setDisplayOrientation(90);
    camera.setParameters(parameters);
}
 
Example 7
Source File: CameraPreview.java    From RecordVideo with Apache License 2.0 5 votes vote down vote up
public boolean manualFocus(Camera camera, Camera.AutoFocusCallback cb, List<Camera.Area> focusAreas
        ,List<Camera.Area> mFocusAreas) {
    //判断系统是否是4.0以上的版本
    if (camera != null && focusAreas != null && SystemVersionUtil.hasICS()) {
        try {
            camera.cancelAutoFocus();
            Camera.Parameters parameters = camera.getParameters();
            if(parameters != null){
                // getMaxNumFocusAreas检测设备是否支持
                if (parameters.getMaxNumFocusAreas() > 0) {
                    parameters.setFocusAreas(focusAreas);
                }
                // getMaxNumMeteringAreas检测设备是否支持
                if (parameters.getMaxNumMeteringAreas() > 0)
                    parameters.setMeteringAreas(mFocusAreas);
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
                camera.setParameters(parameters);
                camera.autoFocus(cb);
                return true;
            }
        } catch (Exception e) {
            if (e != null)
                Log.e(" ", "autoFocus", e);
        }
    }
    return false;
}
 
Example 8
Source File: CameraListener.java    From ShaderEditor with MIT License 5 votes vote down vote up
private boolean startPreview(Camera camera) {
	if (pausing || camera == null) {
		return false;
	}

	camera.setDisplayOrientation(frameOrientation);

	Camera.Parameters parameters = camera.getParameters();
	parameters.setRotation(frameOrientation);
	setPreviewSize(parameters);
	setFastestFps(parameters);
	setFocusMode(parameters);
	camera.setParameters(parameters);

	surfaceTexture = new SurfaceTexture(cameraTextureId);
	surfaceTexture.setOnFrameAvailableListener(
			new SurfaceTexture.OnFrameAvailableListener() {
				@Override
				public void onFrameAvailable(SurfaceTexture st) {
					synchronized (CameraListener.this) {
						available = true;
					}
				}
			});

	try {
		camera.setPreviewTexture(surfaceTexture);
	} catch (IOException e) {
		return false;
	}

	cam = camera;
	camera.startPreview();
	return true;
}
 
Example 9
Source File: CameraConfigurationManager.java    From Android with MIT License 5 votes vote down vote up
public 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;
	}

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

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

	parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
	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;
	}

	/** Set camera preview for vertical screen */
	camera.setDisplayOrientation(90);
}
 
Example 10
Source File: CameraConfigurationManager.java    From iscanner_android with MIT License 5 votes vote down vote up
/**
 * Sets the camera up to take preview images which are used for both preview
 * and decoding. We detect the preview format here so that
 * buildLuminanceSource() can build an appropriate LuminanceSource subclass.
 * In the future we may want to force YUV420SP as it's the smallest, and the
 * planar Y can be used for barcode scanning without a copy in some cases.
 */
void setDesiredCameraParameters(Camera camera) {
	Camera.Parameters parameters = camera.getParameters();
	Log.d(TAG, "Setting preview size: " + cameraResolution);
	parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
	setFlash(parameters);
	setZoom(parameters);
	// setSharpness(parameters);
	// modify here
	camera.setDisplayOrientation(270);
	camera.setParameters(parameters);
}
 
Example 11
Source File: CameraConfigurationManager.java    From android-mrz-reader with Apache License 2.0 5 votes vote down vote up
void setTorch(Camera camera, boolean newSetting) {
    Camera.Parameters parameters = camera.getParameters();
    doSetTorch(parameters, newSetting);
    camera.setParameters(parameters);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_TOGGLE_LIGHT, false);
    if (currentSetting != newSetting) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(PreferencesActivity.KEY_TOGGLE_LIGHT, newSetting);
        editor.commit();
    }
}
 
Example 12
Source File: CameraConfigManager.java    From StarBarcode with Apache License 2.0 5 votes vote down vote up
/**
 * 设置预期的相机参数
 * @param camera
 */
void setDesiredCameraParameters(OpenCamera camera) {
    Camera theCamera = camera.getCamera();
    Camera.Parameters parameters = theCamera.getParameters();
    parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
    theCamera.setParameters(parameters);
    theCamera.setDisplayOrientation(cwNeededRotation);
}
 
Example 13
Source File: CameraSource.java    From Document-Scanner with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Opens the camera and applies the user settings.
 *
 * @throws RuntimeException if the method fails
 */
@SuppressLint("InlinedApi")
private Camera createCamera() {
    int requestedCameraId = getIdForRequestedCamera(mFacing);
    if (requestedCameraId == -1) {
        throw new RuntimeException("Could not find requested camera.");
    }

    Camera camera;
    camera = Camera.open(requestedCameraId);

    SizePair sizePair = selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight);
    if (sizePair == null) {
        throw new RuntimeException("Could not find suitable preview size.");
    }
    Size pictureSize = sizePair.pictureSize();
    mPreviewSize = sizePair.previewSize();

    int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps);
    if (previewFpsRange == null) {
        throw new RuntimeException("Could not find suitable preview frames per second range.");
    }

    Camera.Parameters parameters = camera.getParameters();

    if (pictureSize != null) {
        parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
    }

    parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    parameters.setPreviewFpsRange(
            previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
            previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
    parameters.setPreviewFormat(ImageFormat.NV21);

    setRotation(camera, parameters, requestedCameraId);

    if (mFocusMode != null) {
        if (parameters.getSupportedFocusModes().contains(
                mFocusMode)) {
            parameters.setFocusMode(mFocusMode);
        } else {
            Log.i(TAG, "Camera focus mode: " + mFocusMode +
                " is not supported on this device.");
        }
    }

    // setting mFocusMode to the one set in the params
    mFocusMode = parameters.getFocusMode();

    if (mFlashMode != null) {
        if (parameters.getSupportedFlashModes().contains(
                mFlashMode)) {
            parameters.setFlashMode(mFlashMode);
        } else {
            Log.i(TAG, "Camera flash mode: " + mFlashMode +
                " is not supported on this device.");
        }
    }

    // setting mFlashMode to the one set in the params
    mFlashMode = parameters.getFlashMode();

    camera.setParameters(parameters);

    // Four frame buffers are needed for working with the camera:
    //
    //   one for the frame that is currently being executed upon in doing detection
    //   one for the next pending frame to process immediately upon completing detection
    //   two for the frames that the camera uses to populate future preview images
    camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback());
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));

    return camera;
}
 
Example 14
Source File: CameraConfigurationManager.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
void setDesiredCameraParameters(OpenCamera camera, boolean safeMode) {

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

    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,
        prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true),
        prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, true),
        safeMode);

    if (!safeMode) {
      if (prefs.getBoolean(PreferencesActivity.KEY_INVERT_SCAN, false)) {
        CameraConfigurationUtils.setInvertColor(parameters);
      }

      if (!prefs.getBoolean(PreferencesActivity.KEY_DISABLE_BARCODE_SCENE_MODE, true)) {
        CameraConfigurationUtils.setBarcodeSceneMode(parameters);
      }

      if (!prefs.getBoolean(PreferencesActivity.KEY_DISABLE_METERING, true)) {
        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;
    }
  }
 
Example 15
Source File: CameraSource.java    From trust-wallet-android-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Opens the camera and applies the user settings.
 *
 * @throws RuntimeException if the method fails
 */
@SuppressLint("InlinedApi")
private Camera createCamera() {
    int requestedCameraId = getIdForRequestedCamera(mFacing);
    if (requestedCameraId == -1) {
        throw new RuntimeException("Could not find requested camera.");
    }
    Camera camera = Camera.open(requestedCameraId);

    SizePair sizePair = selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight);
    if (sizePair == null) {
        throw new RuntimeException("Could not find suitable preview size.");
    }
    Size pictureSize = sizePair.pictureSize();
    mPreviewSize = sizePair.previewSize();

    int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps);
    if (previewFpsRange == null) {
        throw new RuntimeException("Could not find suitable preview frames per second range.");
    }

    Camera.Parameters parameters = camera.getParameters();

    if (pictureSize != null) {
        parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
    }

    parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    parameters.setPreviewFpsRange(
            previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
            previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
    parameters.setPreviewFormat(ImageFormat.NV21);

    setRotation(camera, parameters, requestedCameraId);

    if (mFocusMode != null) {
        if (parameters.getSupportedFocusModes().contains(
                mFocusMode)) {
            parameters.setFocusMode(mFocusMode);
        } else {
            Log.i(TAG, "Camera focus mode: " + mFocusMode + " is not supported on this device.");
        }
    }

    // setting mFocusMode to the one set in the params
    mFocusMode = parameters.getFocusMode();

    if (mFlashMode != null) {
        if (parameters.getSupportedFlashModes().contains(
                mFlashMode)) {
            parameters.setFlashMode(mFlashMode);
        } else {
            Log.i(TAG, "Camera flash mode: " + mFlashMode + " is not supported on this device.");
        }
    }

    // setting mFlashMode to the one set in the params
    mFlashMode = parameters.getFlashMode();

    camera.setParameters(parameters);

    // Four frame buffers are needed for working with the camera:
    //
    //   one for the frame that is currently being executed upon in doing detection
    //   one for the next pending frame to process immediately upon completing detection
    //   two for the frames that the camera uses to populate future preview images
    camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback());
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
    camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));

    return camera;
}
 
Example 16
Source File: CameraManager.java    From QRScanner with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Opens the camera driver and initializes the hardware parameters.
 *
 * @param holder The surface object which the camera will draw preview frames
 *               into.
 * @throws IOException Indicates the camera driver failed to open.
 */
public synchronized void openDriver(SurfaceHolder holder) throws IOException {
    Camera theCamera = camera;
    if (theCamera == null) {

        if (requestedCameraId >= 0) {
            theCamera = OpenCameraInterface.open(requestedCameraId);
        } else {
            theCamera = OpenCameraInterface.open();
        }

        if (theCamera == null) {
            throw new IOException();
        }
        camera = theCamera;
    }
    theCamera.setPreviewDisplay(holder);

    if (!initialized) {
        initialized = true;
        configManager.initFromCameraParameters(theCamera);
    }

    Camera.Parameters parameters = theCamera.getParameters();
    String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save
    // these,
    // temporarily
    try {
        configManager.setDesiredCameraParameters(theCamera, false);
    } catch (RuntimeException re) {
        // Driver failed
        Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters");
        Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened);
        // Reset:
        if (parametersFlattened != null) {
            parameters = theCamera.getParameters();
            parameters.unflatten(parametersFlattened);
            try {
                theCamera.setParameters(parameters);
                configManager.setDesiredCameraParameters(theCamera, true);
            } catch (RuntimeException re2) {
                // Well, darn. Give up
                Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration");
            }
        }
    }

}
 
Example 17
Source File: FaceUtil.java    From ViseFace with Apache License 2.0 4 votes vote down vote up
/**
 * 在摄像头启动前设置参数
 *
 * @param cameraPreview
 * @param faceDetector
 * @param camera
 * @param cameraId
 * @param width
 * @param height
 * @param <T>
 */
public static <T> int setCameraParams(CameraPreview cameraPreview, IFaceDetector<T> faceDetector, Camera camera,
                                      int cameraId, int width, int height) {
    if (camera == null) {
        return 0;
    }
    // 获取摄像头支持的pictureSize列表
    Camera.Parameters parameters = camera.getParameters();
    List<Camera.Size> pictureSizeList = parameters.getSupportedPictureSizes();
    // 从列表中选择合适的分辨率
    Point pictureSize = FaceUtil.findBestResolution(pictureSizeList, new Point(width, height), true, 0.15f);
    // 根据选出的PictureSize重新设置SurfaceView大小
    parameters.setPictureSize(pictureSize.x, pictureSize.y);

    // 获取摄像头支持的PreviewSize列表
    List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
    Point preSize = FaceUtil.findBestResolution(previewSizeList, new Point(width, height), false, 0.15f);
    parameters.setPreviewSize(preSize.x, preSize.y);

    float w = preSize.x;
    float h = preSize.y;
    float scale = 1.0f;
    int tempW = (int) (height * (h / w));
    int tempH = (int) (width * (w / h));
    if (cameraPreview != null) {
        if (tempW >= width) {
            cameraPreview.setLayoutParams(new FrameLayout.LayoutParams(tempW, height));
            scale = tempW / h;
        } else if (tempH >= height) {
            cameraPreview.setLayoutParams(new FrameLayout.LayoutParams(width, tempH));
            scale = tempH / w;
        } else {
            cameraPreview.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        }
    }
    if (faceDetector != null) {
        faceDetector.setZoomRatio(5f * scale);
        faceDetector.setPreviewWidth((int) w);
        faceDetector.setPreviewHeight((int) h);
    }

    parameters.setJpegQuality(100);
    if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
        // 连续对焦
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
    }
    camera.cancelAutoFocus();
    int displayOrientation = setCameraDisplayOrientation(cameraPreview.getContext(), faceDetector, camera, cameraId);
    camera.setParameters(parameters);
    return displayOrientation;
}
 
Example 18
Source File: CameraConfigurationManager.java    From reacteu-app with MIT License 4 votes vote down vote up
void setDesiredCameraParameters(Camera camera, boolean safeMode) {
  // Checkout screen orientation
  int rotation = context.getApplicationContext().getResources().getConfiguration().orientation;

  WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  Display display = windowManager.getDefaultDisplay();
  int deviceSpecificRotation = display.getRotation();

  if (rotation == Configuration.ORIENTATION_PORTRAIT) {
    if (deviceSpecificRotation == Surface.ROTATION_0 || deviceSpecificRotation == Surface.ROTATION_90) {
      camera.setDisplayOrientation(90);
    } else {
      camera.setDisplayOrientation(270);
    }
  } else {
    // landscape
    if (deviceSpecificRotation == Surface.ROTATION_180 || deviceSpecificRotation == Surface.ROTATION_270) {
      camera.setDisplayOrientation(180);
    }
  }

  Camera.Parameters parameters = camera.getParameters();

  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);

  String focusMode = null;
  if (prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true)) {
    if (safeMode || prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, false)) {
      focusMode = findSettableValue(parameters.getSupportedFocusModes(),
          Camera.Parameters.FOCUS_MODE_AUTO);
    } else {
      focusMode = findSettableValue(parameters.getSupportedFocusModes(),
          "continuous-picture", // Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE in 4.0+
          "continuous-video",   // Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO in 4.0+
          Camera.Parameters.FOCUS_MODE_AUTO);
    }
  }
  // Maybe selected auto-focus but not available, so fall through here:
  if (!safeMode && focusMode == null) {
    focusMode = findSettableValue(parameters.getSupportedFocusModes(),
        Camera.Parameters.FOCUS_MODE_MACRO,
        "edof"); // Camera.Parameters.FOCUS_MODE_EDOF in 2.2+
  }
  if (focusMode != null) {
    parameters.setFocusMode(focusMode);
  }

  parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
  camera.setParameters(parameters);
}
 
Example 19
Source File: CameraManager.java    From GOpenSource_AppKit_Android_AS with MIT License 4 votes vote down vote up
/**
 * Opens the camera driver and initializes the hardware parameters.
 * 
 * @param holder
 *            The surface object which the camera will draw preview frames
 *            into.
 * @throws IOException
 *             Indicates the camera driver failed to open.
 */
public synchronized void openDriver(SurfaceHolder holder) throws IOException {
	Camera theCamera = camera;
	if (theCamera == null) {

		if (requestedCameraId >= 0) {
			theCamera = OpenCameraInterface.open(requestedCameraId);
		} else {
			theCamera = OpenCameraInterface.open();
		}

		if (theCamera == null) {
			throw new IOException();
		}
		camera = theCamera;
	}
	theCamera.setPreviewDisplay(holder);

	if (!initialized) {
		initialized = true;
		configManager.initFromCameraParameters(theCamera);
	}

	Camera.Parameters parameters = theCamera.getParameters();
	String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save
																					// these,
																					// temporarily
	try {
		configManager.setDesiredCameraParameters(theCamera, false);
	} catch (RuntimeException re) {
		// Driver failed
		Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters");
		Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened);
		// Reset:
		if (parametersFlattened != null) {
			parameters = theCamera.getParameters();
			parameters.unflatten(parametersFlattened);
			try {
				theCamera.setParameters(parameters);
				configManager.setDesiredCameraParameters(theCamera, true);
			} catch (RuntimeException re2) {
				// Well, darn. Give up
				Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration");
			}
		}
	}

}
 
Example 20
Source File: CameraManager.java    From ScanZbar with Apache License 2.0 4 votes vote down vote up
/**
 * Opens the camera driver and initializes the hardware parameters.
 * <p>
 * <p>
 * The surface object which the camera will draw preview frames
 * into.
 *
 * @throws IOException Indicates the camera driver failed to open.
 */
public synchronized void openDriver(SurfaceHolder holder) throws IOException {
    Camera theCamera = camera;
    if (theCamera == null) {
        theCamera = Camera.open();
        if (theCamera == null) {
            throw new IOException();
        }
        camera = theCamera;
    }
    // 设置摄像头预览view
    theCamera.setPreviewDisplay(holder);

    if (!initialized) {
        initialized = true;
        configManager.initFromCameraParameters(theCamera);
    }

    Camera.Parameters parameters = theCamera.getParameters();
    String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save
    // temporarily
    try {
        configManager.setDesiredCameraParameters(theCamera, false);
    } catch (RuntimeException re) {
        // Driver failed
        Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters");
        Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened);
        // Reset:
        if (parametersFlattened != null) {
            parameters = theCamera.getParameters();
            parameters.unflatten(parametersFlattened);
            try {
                theCamera.setParameters(parameters);
                configManager.setDesiredCameraParameters(theCamera, true);
            } catch (RuntimeException re2) {
                // Well, darn. Give up
                Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration");
            }
        }
    }

}