Here are the examples of the java api android.hardware.Camera taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1027 Examples
19
Source : ProcessDataTask.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public clreplaced ProcessDataTask extends AsyncTask<Void, Void, String> {
private Camera mCamera;
private byte[] mData;
private Delegate mDelegate;
public ProcessDataTask(Camera camera, byte[] data, Delegate delegate) {
mCamera = camera;
mData = data;
mDelegate = delegate;
}
public ProcessDataTask perform() {
if (Build.VERSION.SDK_INT >= 11) {
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
execute();
}
return this;
}
public void cancelTask() {
if (getStatus() != Status.FINISHED) {
cancel(true);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
mDelegate = null;
}
@Override
protected String doInBackground(Void... params) {
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size size = parameters.getPreviewSize();
int width = size.width;
int height = size.height;
byte[] rotatedData = new byte[mData.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
rotatedData[x * height + height - y - 1] = mData[x + y * width];
}
}
int tmp = width;
width = height;
height = tmp;
try {
if (mDelegate == null) {
return null;
}
return mDelegate.processData(rotatedData, width, height, false);
} catch (Exception e1) {
try {
return mDelegate.processData(rotatedData, width, height, true);
} catch (Exception e2) {
return null;
}
}
}
public interface Delegate {
String processData(byte[] data, int width, int height, boolean isRetry);
}
}
19
Source : CameraPreview.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public clreplaced CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = CameraPreview.clreplaced.getSimpleName();
private Camera mCamera;
private boolean mPreviewing = true;
private boolean mAutoFocus = true;
private boolean mSurfaceCreated = false;
private CameraConfigurationManager mCameraConfigurationManager;
public CameraPreview(Context context) {
super(context);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mCameraConfigurationManager = new CameraConfigurationManager(getContext());
mCameraConfigurationManager.initFromCameraParameters(mCamera);
getHolder().addCallback(this);
if (mPreviewing) {
requestLayout();
} else {
showCameraPreview();
}
}
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mSurfaceCreated = true;
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if (surfaceHolder.getSurface() == null) {
return;
}
stopCameraPreview();
post(new Runnable() {
public void run() {
showCameraPreview();
}
});
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mSurfaceCreated = false;
stopCameraPreview();
}
public void showCameraPreview() {
if (mCamera != null) {
try {
mPreviewing = true;
mCamera.setPreviewDisplay(getHolder());
mCameraConfigurationManager.setDesiredCameraParameters(mCamera);
mCamera.startPreview();
if (mAutoFocus) {
mCamera.autoFocus(autoFocusCB);
}
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
}
}
public void stopCameraPreview() {
if (mCamera != null) {
try {
removeCallbacks(doAutoFocus);
mPreviewing = false;
mCamera.cancelAutoFocus();
mCamera.setOneShotPreviewCallback(null);
mCamera.stopPreview();
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
}
}
public void openFlashlight() {
if (flashLightAvaliable()) {
mCameraConfigurationManager.openFlashlight(mCamera);
}
}
public void closeFlashlight() {
if (flashLightAvaliable()) {
mCameraConfigurationManager.closeFlashlight(mCamera);
}
}
private boolean flashLightAvaliable() {
return mCamera != null && mPreviewing && mSurfaceCreated && getContext().getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (mCamera != null && mPreviewing && mAutoFocus && mSurfaceCreated) {
mCamera.autoFocus(autoFocusCB);
}
}
};
Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
postDelayed(doAutoFocus, 1000);
}
};
}
19
Source : CameraPreview.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mCameraConfigurationManager = new CameraConfigurationManager(getContext());
mCameraConfigurationManager.initFromCameraParameters(mCamera);
getHolder().addCallback(this);
if (mPreviewing) {
requestLayout();
} else {
showCameraPreview();
}
}
}
19
Source : CameraConfigurationManager.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public void closeFlashlight(Camera camera) {
doSetTorch(camera, false);
}
19
Source : CameraConfigurationManager.java
with Apache License 2.0
from zuoweitan
with Apache License 2.0
from zuoweitan
public void openFlashlight(Camera camera) {
doSetTorch(camera, true);
}
19
Source : CameraUtils.java
with Apache License 2.0
from zhouzhuo810
with Apache License 2.0
from zhouzhuo810
/**
* Get the Camera instance
* @return camera
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
19
Source : CameraHelp.java
with MIT License
from Zhaoss
with MIT License
from Zhaoss
/**
* Created by zhaoshuang on 2018/7/20.
*/
public clreplaced CameraHelp {
// 默认录制大小
private int[] previewSize = new int[2];
private final static int defaultSize = 1280 * 720;
private final static float defaultRatio = 9f / 16f;
private Camera mCamera;
private Camera.PreviewCallback previewCallback;
private int displayOrientation;
private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
private boolean isFlashOpen;
public void openCamera(Activity activity, int cameraId, SurfaceHolder surfaceHolder) {
try {
if (mCamera != null) {
release();
}
this.cameraId = cameraId;
mCamera = Camera.open(cameraId);
displayOrientation = getCameraDisplayOrientation(activity, cameraId);
mCamera.setDisplayOrientation(displayOrientation);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.setPreviewCallback(previewCallback);
Camera.Parameters parameters = mCamera.getParameters();
previewSize = getPreviewSize();
parameters.setPreviewSize(previewSize[0], previewSize[1]);
parameters.setFocusMode(getAutoFocus());
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setPreviewFormat(ImageFormat.NV21);
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
// 自动对焦
private String getAutoFocus() {
Camera.Parameters parameters = mCamera.getParameters();
List<String> focusModes = parameters.getSupportedFocusModes();
if (((Build.MODEL.startsWith("GT-I950")) || (Build.MODEL.endsWith("SCH-I959")) || (Build.MODEL.endsWith("MEIZU MX3"))) && focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
return Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE;
} else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
return Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO;
} else {
return Camera.Parameters.FOCUS_MODE_FIXED;
}
}
// 摄像大小
private int[] getPreviewSize() {
int[] previewSize = new int[2];
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
for (Camera.Size size : supportedPreviewSizes) {
if ((size.width * size.height == defaultSize) && (size.width * 1f / size.height == defaultRatio)) {
previewSize[0] = size.width;
previewSize[1] = size.height;
return previewSize;
}
}
int difference = 0;
int position = 0;
for (int x = 0; x < supportedPreviewSizes.size(); x++) {
Camera.Size size = supportedPreviewSizes.get(x);
int n = Math.abs(defaultSize - size.width * size.height);
if (x == 0 || difference > n) {
difference = n;
position = x;
}
}
Camera.Size size = supportedPreviewSizes.get(position);
previewSize[0] = size.width;
previewSize[1] = size.height;
return previewSize;
}
public int getCameraId() {
return cameraId;
}
public void changeFlash() {
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
String flashMode = parameters.getFlashMode();
List<String> flashModeList = parameters.getSupportedFlashModes();
if (!isFlashOpen) {
if (flashModeList != null && flashModeList.contains("torch") && !"torch".equals(flashMode)) {
try {
parameters.setFlashMode("torch");
mCamera.setParameters(parameters);
isFlashOpen = true;
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
if (flashModeList != null && flashModeList.contains("off") && !"off".equals(flashMode)) {
try {
parameters.setFlashMode("off");
mCamera.setParameters(parameters);
isFlashOpen = false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public boolean isFlashOpen() {
return isFlashOpen;
}
public String getFlashMode() {
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
return parameters.getFlashMode();
}
return "";
}
public void release() {
if (mCamera != null) {
try {
isFlashOpen = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int getDisplayOrientation() {
return displayOrientation;
}
public int getWidth() {
return previewSize[0];
}
public int getHeight() {
return previewSize[1];
}
public void setPreviewCallback(Camera.PreviewCallback previewCallback) {
this.previewCallback = previewCallback;
}
public void callFocusMode() {
try {
List<String> focusModes = mCamera.getParameters().getSupportedFocusModes();
if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
focusOnTouch(previewSize[0] / 2, previewSize[1] / 2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void focusOnTouch(int x, int y) {
Rect rect = new Rect(x - 100, y - 100, x + 100, y + 100);
int left = rect.left * 2000 / previewSize[0] - 1000;
int top = rect.top * 2000 / previewSize[1] - 1000;
int right = rect.right * 2000 / previewSize[0] - 1000;
int bottom = rect.bottom * 2000 / previewSize[1] - 1000;
// 如果超出了(-1000,1000)到(1000, 1000)的范围,则会导致相机崩溃
if (left < -1000) {
left = 1000;
}
if (top < -1000) {
top = -1000;
}
if (right > 1000) {
right = 1000;
}
if (bottom > 1000) {
bottom = 1000;
}
final String focusMode = mCamera.getParameters().getFocusMode();
Rect rect1 = new Rect(left, top, right, bottom);
// 先获取当前相机的参数配置对象
Camera.Parameters parameters = mCamera.getParameters();
// 设置聚焦模式
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (parameters.getMaxNumFocusAreas() > 0) {
List<Camera.Area> focusAreas = new ArrayList<>();
focusAreas.add(new Camera.Area(rect1, 1000));
parameters.setFocusAreas(focusAreas);
}
// 先要取消掉进程中所有的聚焦功能
mCamera.cancelAutoFocus();
// 一定要记得把相应参数设置给相机
mCamera.setParameters(parameters);
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
Camera.Parameters parame = camera.getParameters();
parame.setFocusMode(focusMode);
camera.setParameters(parame);
}
});
}
// 得到摄像旋转角度
private int getCameraDisplayOrientation(Activity activity, int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
// compensate the mirror
result = (360 - result) % 360;
} else {
// back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
}
19
Source : DecoderWrapper.java
with MIT License
from yuriy-budiyev
with MIT License
from yuriy-budiyev
final clreplaced DecoderWrapper {
private final Camera mCamera;
private final Camera.CameraInfo mCameraInfo;
private final Decoder mDecoder;
private final Point mImageSize;
private final Point mPreviewSize;
private final Point mViewSize;
private final int mDisplayOrientation;
private final boolean mReverseHorizontal;
private final boolean mAutoFocusSupported;
private final boolean mFlashSupported;
public DecoderWrapper(@NonNull final Camera camera, @NonNull final Camera.CameraInfo cameraInfo, @NonNull final Decoder decoder, @NonNull final Point imageSize, @NonNull final Point previewSize, @NonNull final Point viewSize, final int displayOrientation, final boolean autoFocusSupported, final boolean flashSupported) {
mCamera = camera;
mCameraInfo = cameraInfo;
mDecoder = decoder;
mImageSize = imageSize;
mPreviewSize = previewSize;
mViewSize = viewSize;
mDisplayOrientation = displayOrientation;
mReverseHorizontal = cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT;
mAutoFocusSupported = autoFocusSupported;
mFlashSupported = flashSupported;
}
@NonNull
public Camera getCamera() {
return mCamera;
}
@NonNull
public Camera.CameraInfo getCameraInfo() {
return mCameraInfo;
}
@NonNull
public Decoder getDecoder() {
return mDecoder;
}
@NonNull
public Point getImageSize() {
return mImageSize;
}
@NonNull
public Point getPreviewSize() {
return mPreviewSize;
}
@NonNull
public Point getViewSize() {
return mViewSize;
}
public int getDisplayOrientation() {
return mDisplayOrientation;
}
public boolean shouldReverseHorizontal() {
return mReverseHorizontal;
}
public boolean isAutoFocusSupported() {
return mAutoFocusSupported;
}
public boolean isFlashSupported() {
return mFlashSupported;
}
public void release() {
mCamera.release();
mDecoder.shutdown();
}
}
19
Source : FrontCamera.java
with Apache License 2.0
from xingaijian
with Apache License 2.0
from xingaijian
/**
* 相机类,相机的调用
*/
public clreplaced FrontCamera {
static final String TAG = "Camera";
Camera mCamera;
int mCurrentCamIndex = 0;
boolean previewing;
public void setCamera(Camera camera) {
this.mCamera = camera;
}
public int getCurrentCamIndex() {
return this.mCurrentCamIndex;
}
public boolean getPreviewing() {
return this.previewing;
}
Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() {
@Override
public void onShutter() {
}
};
Camera.PictureCallback rawPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
}
};
Camera.PictureCallback jpegPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.i(TAG, "已经获取了bitmap:" + bitmap.toString());
previewing = false;
// 需要保存可执行下面
/* new Thread(new Runnable() {
@Override
public void run() {
String filePath = ImageUtil.getSaveImgePath();
File file = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
fos.write(data);
ImageUtil.saveImage(file, data, filePath);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();*/
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 重新开启预览 ,不然不能继续拍照
mCamera.startPreview();
previewing = true;
}
};
// 初始化相机
public Camera initCamera() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
Log.e(TAG, "cameraCount: " + cameraCount);
previewing = true;
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
// 在这里打开的是前置摄像头,可修改打开后置OR前置
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
try {
cam = Camera.open(camIdx);
mCurrentCamIndex = camIdx;
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
/**
* 停止相机
* @param mCamera 需要停止的相机对象
*/
public void StopCamera(Camera mCamera) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
previewing = false;
}
/**
* 旋转屏幕后自动适配(若只用到竖的,也可不要)
* 已经在manifests中让此Activity只能竖屏了
* @param activity 相机显示在的Activity
* @param cameraId 相机的ID
* @param camera 相机对象
*/
public static void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
// compensate the mirror
result = (360 - result) % 360;
} else {
// back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
19
Source : FrontCamera.java
with Apache License 2.0
from xingaijian
with Apache License 2.0
from xingaijian
public void setCamera(Camera camera) {
this.mCamera = camera;
}
19
Source : FaceTask.java
with Apache License 2.0
from xingaijian
with Apache License 2.0
from xingaijian
/**
* 单独的任务类。继承AsyncTask,来处理从相机实时获取的耗时操作
*/
public clreplaced FaceTask extends AsyncTask {
private byte[] mData;
Camera mCamera;
private static final String TAG = "CameraTag";
// 构造函数
FaceTask(byte[] data, Camera camera) {
this.mData = data;
this.mCamera = camera;
}
@Override
protected Object doInBackground(Object[] params) {
Camera.Parameters parameters = mCamera.getParameters();
int imageFormat = parameters.getPreviewFormat();
int w = parameters.getPreviewSize().width;
int h = parameters.getPreviewSize().height;
Rect rect = new Rect(0, 0, w, h);
YuvImage yuvImg = new YuvImage(mData, imageFormat, w, h, null);
try {
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
yuvImg.compressToJpeg(rect, 100, outputstream);
Bitmap rawbitmap = BitmapFactory.decodeByteArray(outputstream.toByteArray(), 0, outputstream.size());
Log.i(TAG, "onPreviewFrame: rawbitmap:" + rawbitmap.toString());
// 若要存储可以用下列代码,格式为jpg
/* BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/fp.jpg"));
img.compressToJpeg(rect, 100, bos);
bos.flush();
bos.close();
mCamera.startPreview();
*/
} catch (Exception e) {
Log.e(TAG, "onPreviewFrame: 获取相机实时数据失败" + e.getLocalizedMessage());
}
return null;
}
}
19
Source : CameraHelper.java
with Apache License 2.0
from xiaxveliang
with Apache License 2.0
from xiaxveliang
/**
* create by xiaxl 2016.08.12
* <p>
* 用opengl 预览摄像头的一些封装
* <p>
* 用opengl预览摄像头,用egl获取opengl绘制的buffer帧进行编码,生成MP4,从而完成视频录制
*/
public clreplaced CameraHelper {
private static final String TAG = CameraHelper.clreplaced.getSimpleName();
// instance
private static CameraHelper INSTANCE = new CameraHelper();
//
public static synchronized CameraHelper getInstance() {
return INSTANCE;
}
// 摄像头对象
private Camera mCamera = null;
// 当前预览摄像头id,默认摄像头为后置摄像头
private int mCurrentPreviewCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
/**
* 获取摄像头的数据
*
* @return
*/
public int getNumberOfCameras() {
return Camera.getNumberOfCameras();
}
/**
* 获取当前预览摄像头id
*
* @return
*/
public int getCurrentPreviewCameraId() {
return mCurrentPreviewCameraId;
}
/**
* 获取预览区域的宽度
*
* @return
*/
public int getPreviewWidth() {
if (mCamera != null) {
final Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
return previewSize.width;
}
return 0;
}
/**
* 获取预览区域的高度
*
* @return
*/
public int getPreviewHeight() {
if (mCamera != null) {
final Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
return previewSize.height;
}
return 0;
}
/**
* 开启摄像头
*
* @param cameraId 开启的摄像头的id
* @param previewSurfaceTexture 预览的SurfaceTexture
*/
public void startPreview(int cameraId, SurfaceTexture previewSurfaceTexture) {
LogUtils.e(TAG, "---startPreview: " + cameraId);
if (previewSurfaceTexture == null) {
LogUtils.e(TAG, "previewSurfaceTexture is null");
return;
}
//
if (cameraId != Camera.CameraInfo.CAMERA_FACING_FRONT && cameraId != Camera.CameraInfo.CAMERA_FACING_BACK) {
LogUtils.e(TAG, "Invalid cameraId: " + cameraId);
return;
}
// 关闭摄像头
stopPreview();
// ---------------------开启摄像头----------------------
// 摄像头Info
Camera.CameraInfo info = new Camera.CameraInfo();
// 获取摄像头数量
int numCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numCameras; i++) {
Camera.getCameraInfo(i, info);
if (info.facing == cameraId) {
// 打开摄像头
mCamera = Camera.open(i);
// 摄像头Id赋值
this.mCurrentPreviewCameraId = cameraId;
break;
}
}
// ---------------------聚焦----------------------
//
final Camera.Parameters params = mCamera.getParameters();
//
final List<String> focusModes = params.getSupportedFocusModes();
// 连续聚焦
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
} else // 自动聚焦
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
// -------------------------------------------
// 可以帮助减少启动录制的时间,如果用opengl预览,用egl获取buffer,用mediacodec录制编码视频,这里好像没有用了
params.setRecordingHint(true);
// --------------------预览区域大小-----------------------
// 推荐的预览区域大小
Camera.Size ppsfv = params.getPreferredPreviewSizeForVideo();
if (ppsfv != null) {
LogUtils.d(TAG, "Camera preferred preview size for video is: " + ppsfv.width + "x" + ppsfv.height);
}
// 支持的预览区域大小
for (Camera.Size size : params.getSupportedPreviewSizes()) {
LogUtils.d(TAG, "supported: " + size.width + "x" + size.height);
}
// 这里采用推荐的预览区域大小
if (ppsfv != null) {
params.setPreviewSize(ppsfv.width, ppsfv.height);
}
// --------------------设置params-----------------------
//
mCamera.setParameters(params);
// --------------------设置预览的SurfaceTexture-----------------------
try {
// 设置预览的SurfaceTexture
mCamera.setPreviewTexture(previewSurfaceTexture);
} catch (final IOException e) {
LogUtils.e(TAG, "IOException:", e);
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
} catch (final RuntimeException e) {
LogUtils.e(TAG, "RuntimeException:", e);
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
// --------------------开启预览-----------------------
if (mCamera != null) {
mCamera.startPreview();
}
}
/**
* stop camera preview
*/
public void stopPreview() {
LogUtils.e(TAG, "---stopPreview---");
// 释放摄像头资源
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
// 重置预览摄像头id
mCurrentPreviewCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
}
19
Source : BaseFaceDetector.java
with Apache License 2.0
from xiaoyaoyou1212
with Apache License 2.0
from xiaoyaoyou1212
/**
* @Description: 识别抽象类
* @author: <a href="http://xiaoyaoyou1212.360doc.com">DAWI</a>
* @date: 2017/8/11 17:28
*/
public abstract clreplaced BaseFaceDetector<T> implements IFaceDetector<T>, Runnable {
private Thread mThread;
private boolean mStopTrack;
private IDataListener<T> mDataListener;
protected DetectorData<T> mDetectorData;
protected Camera mCamera;
protected int mCameraId;
// 缩放比例
protected float mZoomRatio;
protected int mCameraWidth;
protected int mCameraHeight;
protected int mPreviewWidth;
protected int mPreviewHeight;
protected int mOrientionOfCamera;
protected int mMaxFacesCount;
protected boolean mOpenCamera = false;
public BaseFaceDetector() {
mDetectorData = new DetectorData<>();
}
@Override
public void run() {
mStopTrack = false;
while (!mStopTrack) {
if (!mOpenCamera) {
continue;
}
detectionFaces();
if (mDataListener != null) {
mDataListener.onDetectorData(mDetectorData);
}
}
}
protected abstract void detectionFaces();
/**
* 开启识别
*/
@Override
public void detector() {
mThread = new Thread(this);
mThread.start();
}
/**
* 释放资源
*/
@Override
public void release() {
if (mDetectorData != null) {
mDetectorData.setFaceData(null);
}
mStopTrack = true;
if (mThread != null) {
mThread.interrupt();
mThread = null;
}
}
/**
* 设置检测监听
*
* @param mDataListener
*/
@Override
public void setDataListener(IDataListener<T> mDataListener) {
this.mDataListener = mDataListener;
}
/**
* 设置预览数据
*
* @param data
* @param camera
*/
@Override
public void setCameraPreviewData(byte[] data, Camera camera) {
if (mDetectorData != null) {
mDetectorData.setFaceData(data);
}
mCamera = camera;
}
/**
* 设置识别最大人脸数量
*
* @param mMaxFacesCount
* @return
*/
@Override
public void setMaxFacesCount(int mMaxFacesCount) {
this.mMaxFacesCount = mMaxFacesCount;
}
/**
* 设置相机高度
*
* @param mCameraHeight 相机高度
* @return
*/
@Override
public void setCameraHeight(int mCameraHeight) {
this.mCameraHeight = mCameraHeight;
}
/**
* 设置相机宽度
*
* @param mCameraWidth 相机宽度
* @return
*/
@Override
public void setCameraWidth(int mCameraWidth) {
this.mCameraWidth = mCameraWidth;
}
/**
* 设置相机方向
*
* @param mOrientionOfCamera 相机方向
* @return
*/
@Override
public void setOrientionOfCamera(int mOrientionOfCamera) {
this.mOrientionOfCamera = mOrientionOfCamera;
}
/**
* 设置缩放比例
*
* @param mZoomRatio
* @return
*/
@Override
public void setZoomRatio(float mZoomRatio) {
this.mZoomRatio = mZoomRatio;
}
/**
* 设置相机是否打开
*
* @param isOpenCamera
*/
@Override
public void setOpenCamera(boolean isOpenCamera) {
this.mOpenCamera = isOpenCamera;
}
/**
* 设置相机ID
*
* @param mCameraId
*/
@Override
public void setCameraId(int mCameraId) {
this.mCameraId = mCameraId;
}
/**
* 设置预览高度
*
* @param mPreviewHeight
*/
@Override
public void setPreviewHeight(int mPreviewHeight) {
this.mPreviewHeight = mPreviewHeight;
}
/**
* 设置预览宽度
*
* @param mPreviewWidth
*/
@Override
public void setPreviewWidth(int mPreviewWidth) {
this.mPreviewWidth = mPreviewWidth;
}
}
19
Source : RecordAiRealUtils.java
with MIT License
from wuqingsen
with MIT License
from wuqingsen
// 获取摄像头
public Camera getBackCamera() {
Camera c = null;
try {
// 0后置,1前置
c = Camera.open(cameraDir);
} catch (Exception e) {
e.printStackTrace();
}
// returns null if camera is unavailable
return c;
}
19
Source : CameraUtils.java
with Apache License 2.0
from wildma
with Apache License 2.0
from wildma
/**
* Author wildma
* Github https://github.com/wildma
* Date 2018/6/24
* Desc ${相机工具类}
*/
public clreplaced CameraUtils {
private static Camera camera;
/**
* 检查是否有相机
*
* @param context
* @return
*/
public static boolean hasCamera(Context context) {
if (context.getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* 打开相机
*
* @return
*/
public static Camera openCamera() {
camera = null;
try {
// attempt to get a Camera instance
camera = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return camera;
}
public static Camera getCamera() {
return camera;
}
/**
* 检查是否有闪光灯
*
* @return true:有,false:无
*/
public static boolean hasFlash(Context context) {
return context.getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
}
19
Source : OpenCamera.java
with Apache License 2.0
from weexteam
with Apache License 2.0
from weexteam
public final clreplaced OpenCamera {
private final int index;
private final Camera camera;
private final CameraFacing facing;
private final int orientation;
public OpenCamera(int index, Camera camera, CameraFacing facing, int orientation) {
this.index = index;
this.camera = camera;
this.facing = facing;
this.orientation = orientation;
}
public Camera getCamera() {
return camera;
}
public CameraFacing getFacing() {
return facing;
}
public int getOrientation() {
return orientation;
}
@Override
public String toString() {
return "Camera #" + index + " : " + facing + ',' + orientation;
}
}
19
Source : CameraImplV1.java
with GNU General Public License v3.0
from vbier
with GNU General Public License v3.0
from vbier
/**
* Concrete camera implementation using old camera API.
*/
clreplaced CameraImplV1 extends AbstractCameraImpl {
private static final String TAG = "HPV-CameraImplV1";
private Camera mCamera;
private volatile boolean mPreviewRunning;
private int mCameraId = -1;
private int mCameraOrientation = 0;
CameraImplV1(Activity context, TextureView previewView, boolean cameraFallback) throws CameraException {
super(context, previewView);
findCameraFacing(Camera.CameraInfo.CAMERA_FACING_FRONT);
if (mCameraId == -1 && cameraFallback) {
findCameraFacing(Camera.CameraInfo.CAMERA_FACING_BACK);
}
if (mCameraId == -1) {
if (cameraFallback) {
throw new CameraException(mActivity.getString(R.string.cameraMissing));
} else {
throw new CameraException(mActivity.getString(R.string.frontCameraMissing));
}
}
}
private void findCameraFacing(int direction) {
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, info);
if (info.facing == direction) {
mCameraId = i;
mCameraOrientation = info.orientation;
Log.v(TAG, "found front-facing camera with id " + i + " and orientation " + mCameraOrientation);
}
}
}
@Override
public void lockCamera() throws CameraException {
if (mCameraId != -1) {
Thread t = new Thread() {
@Override
public void run() {
try {
mCamera = Camera.open(mCameraId);
setDeviceRotation(mDeviceOrientation);
} catch (RuntimeException e) {
// TODO. throw new CameraException(mActivity.getString(R.string.openCameraFailed), e);
}
}
};
t.start();
try {
t.join();
} catch (InterruptedException e) {
throw new CameraException(mActivity.getString(R.string.openCameraFailed), e);
}
} else if (mCamera == null) {
throw new CameraException(mActivity.getString(R.string.frontCameraMissing));
}
}
@Override
public void setDeviceRotation(int deviceRotation) {
if (mCamera != null) {
mActivity.runOnUiThread(() -> mPreviewView.setTransform(new Matrix()));
int result = (mCameraOrientation + deviceRotation * 90) % 360;
result = (360 - result) % 360;
Log.v(TAG, "setting camera display orientation " + result);
mCamera.setDisplayOrientation(result);
mDeviceOrientation = deviceRotation;
}
}
@Override
public void unlockCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
@Override
public boolean isCameraLocked() {
return mCamera != null;
}
@Override
public void startPreview(SurfaceTexture surface, IPreviewListener previewListener) {
if (mPreviewRunning) {
previewListener.started();
return;
}
if (mCamera != null) {
Log.v(TAG, "trying to start preview...");
try {
mCamera.setPreviewTexture(surface);
Camera.Parameters parameters = mCamera.getParameters();
Point previewSize = chooseOptimalSize(toPointArray(parameters.getSupportedPictureSizes()));
parameters.setPreviewSize(previewSize.x, previewSize.y);
parameters.setPictureSize(previewSize.x, previewSize.y);
mCamera.setParameters(parameters);
mCamera.setPreviewCallback((bytes, camera) -> {
if (!mPreviewRunning) {
mPreviewRunning = true;
previewListener.started();
}
for (ILumaListener l : mListeners) {
if (l.needsPreview()) {
Log.v(TAG, "preview image available and needed: size " + previewSize.x + "x" + previewSize.y);
l.preview(LumaData.extractLuma(bytes, previewSize.x, previewSize.y));
}
}
});
mCamera.startPreview();
} catch (IOException e) {
previewListener.exception(e);
previewListener.error(mActivity.getString(R.string.errorSettingTexture));
}
} else {
previewListener.error(mActivity.getString(R.string.frontCameraMissing));
}
}
@Override
public void stopPreview() {
if (mCamera != null && mPreviewRunning) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mPreviewRunning = false;
}
}
@Override
public boolean isPreviewRunning() {
return mPreviewRunning;
}
@Override
public void takePicture(IPictureListener iPictureHandler) {
if (isPreviewRunning()) {
mCamera.takePicture(null, null, (bytes, camera) -> {
byte[] data = new byte[bytes.length];
System.arraycopy(bytes, 0, data, 0, bytes.length);
iPictureHandler.picture(data);
});
} else {
throw new IllegalStateException(mActivity.getString(R.string.camNotInitialized));
}
}
@Override
public int getCameraOrientation() {
return mCameraOrientation;
}
private Point[] toPointArray(List<Camera.Size> supportedPictureSizes) {
ArrayList<Point> result = new ArrayList<>();
for (Camera.Size s : supportedPictureSizes) {
result.add(new Point(s.width, s.height));
}
return result.toArray(new Point[0]);
}
}
19
Source : CameraMgr.java
with Apache License 2.0
from Vanish136
with Apache License 2.0
from Vanish136
/**
* Created by LWK
* TODO 相机管理类
* 2016/11/1
*/
public clreplaced CameraMgr {
private final String TAG = "CameraMgr";
private Camera mCamera;
private int mCameraId = -1;
private boolean mIsLightOn;
private int mPreviewWidth;
private int mPreviewHeight;
public boolean initCamera(Context context, SurfaceHolder holder) throws IOException {
releaseCameraResource();
// 有打开过就直接打开
if (mCameraId != -1) {
mCamera = Camera.open(mCameraId);
} else {
// 没有打开过默认打开后置摄像头
if (checkCameraFacing(Camera.CameraInfo.CAMERA_FACING_BACK))
mCamera = Camera.open(mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK);
}
if (mCamera == null)
return false;
setPortrait();
setOrientation(context);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
return true;
}
/**
* 检查是否有摄像头
*
* @param facing 前置还是后置
*/
private boolean checkCameraFacing(int facing) {
int cameraCount = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, info);
if (facing == info.facing) {
return true;
}
}
return false;
}
// 设置竖屏
private void setPortrait() {
if (mCamera != null) {
// 设置竖屏
Camera.Parameters params = mCamera.getParameters();
params.set("orientation", "portrait");
mCamera.setParameters(params);
}
}
// 设置旋转角度
private void setOrientation(Context context) {
if (mCamera != null) {
if (context instanceof Activity) {
Activity activity = (Activity) context;
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(mCameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees + 360) % 360;
}
mCamera.setDisplayOrientation(result);
} else {
// 设置旋转角度
if (mCameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
mCamera.setDisplayOrientation(90);
else
mCamera.setDisplayOrientation(270);
}
}
}
public void unlock() {
if (mCamera != null)
mCamera.unlock();
}
public void lock() {
if (mCamera != null)
mCamera.lock();
}
/**
* 获取最优预览尺寸
*
* @param targetHeight
*/
public Camera.Size getOptimalPreviewSize(int targetHeight) {
if (mCamera == null)
return null;
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
final double MIN_ASPECT_RATIO = 1.0;
final double MAX_ASPECT_RATIO = 1.7;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (ratio < MIN_ASPECT_RATIO || ratio > MAX_ASPECT_RATIO)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
/**
* 调整预览尺寸
*/
public void adjustPreviewSize(Camera.Size size, SurfaceHolder holder) {
if (mCamera != null) {
if (holder.getSurface() == null)
return;
try {
mCamera.stopPreview();
} catch (Exception e) {
}
Camera.Parameters parameters = mCamera.getParameters();
// 这才是支持的录制尺寸宽度
mPreviewWidth = size.width;
// 这才是支持的录制尺寸高度
mPreviewHeight = size.height;
parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
mCamera.setParameters(parameters);
try {
mCamera.startPreview();
} catch (Exception e) {
}
}
}
/**
* 设置相机对焦模式
*
* @param focusMode
*/
public void setCameraFocusMode(String focusMode) {
if (mCamera == null)
return;
Camera.Parameters parameters = mCamera.getParameters();
List<String> sfm = parameters.getSupportedFocusModes();
if (sfm.contains(focusMode)) {
parameters.setFocusMode(focusMode);
}
mCamera.setParameters(parameters);
}
/**
* 开启闪光灯
*/
public boolean openFlashLight() {
if (mCamera != null && !mIsLightOn) {
try {
Camera.Parameters parameters = mCamera.getParameters();
if (parameters == null)
return false;
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes == null)
return false;
String flashMode = parameters.getFlashMode();
if (!Camera.Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
if (flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
return mIsLightOn = true;
}
}
} catch (Exception e) {
Log.e(TAG, "openFlashLight fail:" + e.toString());
return false;
}
}
return false;
}
/**
* 关闭闪光灯
*/
public boolean closeFlashLight() {
if (mCamera != null && mIsLightOn) {
try {
Camera.Parameters parameters = mCamera.getParameters();
if (parameters == null)
return false;
List<String> flashModes = parameters.getSupportedFlashModes();
String flashMode = parameters.getFlashMode();
if (flashModes == null)
return false;
if (!Camera.Parameters.FLASH_MODE_OFF.equals(flashMode)) {
if (flashModes.contains(Camera.Parameters.FLASH_MODE_OFF)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameters);
mIsLightOn = false;
return true;
}
}
} catch (Exception e) {
Log.e(TAG, "closeFlashLight fail:" + e.toString());
return false;
}
}
return false;
}
public Camera getCamera() {
return mCamera;
}
public int getCameraId() {
return mCameraId;
}
public boolean isLightOn() {
return mIsLightOn;
}
/**
* 获取预览尺寸宽度
*/
public int getPreviewWidth() {
return mPreviewWidth;
}
/**
* 获取预览尺寸高度
*/
public int getPreviewHeight() {
return mPreviewHeight;
}
/**
* 释放摄像头资源
*/
public void releaseCameraResource() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
}
19
Source : ImageRenderer.java
with Apache License 2.0
from vanhung1710
with Apache License 2.0
from vanhung1710
public void setUpSurfaceTexture(final Camera camera) {
runOnDraw(new Runnable() {
@Override
public void run() {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mSurfaceTexture = new SurfaceTexture(textures[0]);
try {
camera.setPreviewTexture(mSurfaceTexture);
camera.setPreviewCallback(ImageRenderer.this);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
19
Source : ImageProcessor.java
with Apache License 2.0
from vanhung1710
with Apache License 2.0
from vanhung1710
/**
* Sets the up camera to be connected to GPUImage to get a filtered preview.
*
* @param camera
* the camera
*/
public void setUpCamera(final Camera camera) {
setUpCamera(camera, 0, false, false);
}
19
Source : EZFilter.java
with MIT License
from uestccokey
with MIT License
from uestccokey
/**
* 设置Camera输入
*
* @param camera 摄像头
* @param size 预览尺寸
* @return
*/
public static CameraBuilder input(Camera camera, Camera.Size size) {
return new CameraBuilder(camera, size);
}
19
Source : CameraBuilder.java
with MIT License
from uestccokey
with MIT License
from uestccokey
/**
* 摄像头处理构造器
*
* @author like
* @date 2017-09-15
*/
public clreplaced CameraBuilder extends EZFilter.Builder {
private Camera mCamera;
private Camera.Size mPreviewSize;
private CameraInput mCameraInput;
public CameraBuilder(Camera camera, Camera.Size size) {
mCamera = camera;
mPreviewSize = size;
}
@Override
public FBORender getStartPointRender(IFitView view) {
if (mCameraInput == null) {
mCameraInput = new CameraInput(view, mCamera, mPreviewSize);
}
return mCameraInput;
}
@Override
public float getAspectRatio(IFitView view) {
return mPreviewSize.height * 1.0f / mPreviewSize.width;
}
@Override
public CameraBuilder addFilter(FilterRender filterRender) {
return (CameraBuilder) super.addFilter(filterRender);
}
@Override
public <T extends FilterRender & IAdjustable> CameraBuilder addFilter(T filterRender, float progress) {
return (CameraBuilder) super.addFilter(filterRender, progress);
}
@Override
public CameraBuilder enableRecord(String outputPath, boolean recordVideo, boolean recordAudio) {
return (CameraBuilder) super.enableRecord(outputPath, recordVideo, recordAudio);
}
}
19
Source : Recorder.java
with Apache License 2.0
from tsy12321
with Apache License 2.0
from tsy12321
/**
* 切换前后摄像头
* @param camera
* @param face
*/
public void switchCamera(Camera camera, int face) {
mBuilder.switchCamera(camera, face);
initFilter();
}
19
Source : CameraPreviewView.java
with Apache License 2.0
from tsy12321
with Apache License 2.0
from tsy12321
public void switchCamera(Camera camera) {
mCamera = camera;
mCameraView.switchCamera();
}
19
Source : CameraPreviewView.java
with Apache License 2.0
from tsy12321
with Apache License 2.0
from tsy12321
/**
* 初始化
* @param camera
* @param width
* @param height
*/
public void init(Camera camera, int width, int height) {
mCamera = camera;
mWidth = width;
mHeight = height;
if (mCameraView != null) {
removeView(mCameraView);
mCameraView = null;
}
// 重新创建一个CameraView加进去
mCameraView = new CameraView(getContext());
addView(mCameraView, 0);
requestLayout();
}
19
Source : OpenCamera.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
/**
* Represents an open {@link Camera} and its metadata, like facing direction and orientation.
*/
public final clreplaced OpenCamera {
private final int index;
private final Camera camera;
private final CameraFacing facing;
private final int orientation;
OpenCamera(int index, Camera camera, CameraFacing facing, int orientation) {
this.index = index;
this.camera = camera;
this.facing = facing;
this.orientation = orientation;
}
public Camera getCamera() {
return camera;
}
public CameraFacing getFacing() {
return facing;
}
public int getOrientation() {
return orientation;
}
@Override
public String toString() {
return "Camera #" + index + " : " + facing + ',' + orientation;
}
}
19
Source : CameraInfo.java
with GNU General Public License v2.0
from TelePlusDev
with GNU General Public License v2.0
from TelePlusDev
public clreplaced CameraInfo {
protected int cameraId;
protected Camera camera;
protected ArrayList<Size> pictureSizes = new ArrayList<>();
protected ArrayList<Size> previewSizes = new ArrayList<>();
protected final int frontCamera;
public CameraInfo(int id, int frontFace) {
cameraId = id;
frontCamera = frontFace;
}
public int getCameraId() {
return cameraId;
}
private Camera getCamera() {
return camera;
}
public ArrayList<Size> getPreviewSizes() {
return previewSizes;
}
public ArrayList<Size> getPictureSizes() {
return pictureSizes;
}
public boolean isFrontface() {
return frontCamera != 0;
}
}
19
Source : OpenCamera.java
with Apache License 2.0
from tarun0
with Apache License 2.0
from tarun0
/**
* Represents an open {@link Camera} and its metadata, like facing direction and orientation.
*/
public final clreplaced OpenCamera {
private final int index;
private final Camera camera;
private final CameraFacing facing;
private final int orientation;
public OpenCamera(int index, Camera camera, CameraFacing facing, int orientation) {
this.index = index;
this.camera = camera;
this.facing = facing;
this.orientation = orientation;
}
public Camera getCamera() {
return camera;
}
public CameraFacing getFacing() {
return facing;
}
public int getOrientation() {
return orientation;
}
@Override
public String toString() {
return "Camera #" + index + " : " + facing + ',' + orientation;
}
}
19
Source : RxCameraTool.java
with Apache License 2.0
from TaoPaox
with Apache License 2.0
from TaoPaox
public clreplaced RxCameraTool {
private static Camera camera;
/**
* 打开闪光灯
*
* @return
*/
public static void openFlashLight() {
try {
if (camera == null) {
camera = Camera.open();
camera.startPreview();
}
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭闪光灯
*
* @return
*/
public static void closeFlashLight() {
try {
if (camera == null) {
} else {
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void takePic(Context mContext, final RxCameraView mCameraView) {
if (mCameraView.isCameraOpened()) {
mCameraView.takePicture();
} else {
mCameraView.start();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
/**
* 延时执行的代码
*/
mCameraView.takePicture();
}
}, // 延时1秒
500);
}
}
public static void initCameraEvent(final Context mContext, final RxCameraView mCameraView, final byte[] data, final String fileDir, final String picName, final double mLongitude, final double mLareplacedude, final boolean isEconomize) {
}
}
19
Source : RxCameraView.java
with Apache License 2.0
from TaoPaox
with Apache License 2.0
from TaoPaox
public clreplaced RxCameraView extends FrameLayout {
private static final String TAG = "CameraView";
Camera camera;
/**
* The camera device faces the opposite direction as the device's screen.
*/
public static final int FACING_BACK = Constants.FACING_BACK;
/**
* The camera device faces the same direction as the device's screen.
*/
public static final int FACING_FRONT = Constants.FACING_FRONT;
/**
* Direction the camera faces relative to device screen.
*/
@IntDef({ FACING_BACK, FACING_FRONT })
@Retention(RetentionPolicy.SOURCE)
public @interface Facing {
}
/**
* Flash will not be fired.
*/
public static final int FLASH_OFF = Constants.FLASH_OFF;
/**
* Flash will always be fired during snapshot.
*/
public static final int FLASH_ON = Constants.FLASH_ON;
/**
* Constant emission of light during preview, auto-focus and snapshot.
*/
public static final int FLASH_TORCH = Constants.FLASH_TORCH;
/**
* Flash will be fired automatically when required.
*/
public static final int FLASH_AUTO = Constants.FLASH_AUTO;
/**
* Flash will be fired in red-eye reduction mode.
*/
public static final int FLASH_RED_EYE = Constants.FLASH_RED_EYE;
/**
* The mode for for the camera device's flash control
*/
@IntDef({ FLASH_OFF, FLASH_ON, FLASH_TORCH, FLASH_AUTO, FLASH_RED_EYE })
public @interface Flash {
}
CameraViewImpl mImpl;
private final CallbackBridge mCallbacks;
private boolean mAdjustViewBounds;
private final DisplayOrientationDetector mDisplayOrientationDetector;
public RxCameraView(Context context) {
this(context, null);
}
public RxCameraView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
Camera1 camera1;
@SuppressWarnings("WrongConstant")
public RxCameraView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (isInEditMode()) {
mCallbacks = null;
mDisplayOrientationDetector = null;
return;
}
// Internal setup
final PreviewImpl preview = createPreviewImpl(context);
mCallbacks = new CallbackBridge();
camera1 = new Camera1(mCallbacks, preview);
mImpl = camera1;
// TODO: 2018/7/3
/* if (Build.VERSION.SDK_INT < 21) {
camera1 = new Camera1(mCallbacks, preview);
mImpl = camera1;
} else if (Build.VERSION.SDK_INT < 23) {
mImpl = new Camera2(mCallbacks, preview, context);
} else {
mImpl = new Camera2Api23(mCallbacks, preview, context);
// camera1 = new Camera1(mCallbacks, preview);
}*/
// TODO: 2018/7/3
// Attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RxCameraView, defStyleAttr, R.style.Widget_CameraView);
mAdjustViewBounds = a.getBoolean(R.styleable.RxCameraView_android_adjustViewBounds, false);
setFacing(a.getInt(R.styleable.RxCameraView_facing, FACING_BACK));
String aspectRatio = a.getString(R.styleable.RxCameraView_aspectRatio);
if (aspectRatio != null) {
setAspectRatio(AspectRatio.parse(aspectRatio));
} else {
setAspectRatio(Constants.DEFAULT_ASPECT_RATIO);
}
setAutoFocus(a.getBoolean(R.styleable.RxCameraView_autoFocus, true));
setFlash(a.getInt(R.styleable.RxCameraView_flash, Constants.FLASH_AUTO));
a.recycle();
// Display orientation detector
mDisplayOrientationDetector = new DisplayOrientationDetector(context) {
@Override
public void onDisplayOrientationChanged(int displayOrientation) {
mImpl.setDisplayOrientation(displayOrientation);
}
};
}
@NonNull
private PreviewImpl createPreviewImpl(Context context) {
PreviewImpl preview;
if (Build.VERSION.SDK_INT < 14) {
preview = new SurfaceViewPreview(context, this);
} else {
preview = new TextureViewPreview(context, this);
}
return preview;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!isInEditMode()) {
mDisplayOrientationDetector.enable(ViewCompat.getDisplay(this));
}
}
@Override
protected void onDetachedFromWindow() {
if (!isInEditMode()) {
mDisplayOrientationDetector.disable();
}
super.onDetachedFromWindow();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isInEditMode()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Handle android:adjustViewBounds
if (mAdjustViewBounds) {
if (!isCameraOpened()) {
mCallbacks.reserveRequestLayoutOnOpen();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
final AspectRatio ratio = getAspectRatio();
replacedert ratio != null;
int height = (int) (MeasureSpec.getSize(widthMeasureSpec) * ratio.toFloat());
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
}
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else if (widthMode != MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
final AspectRatio ratio = getAspectRatio();
replacedert ratio != null;
int width = (int) (MeasureSpec.getSize(heightMeasureSpec) * ratio.toFloat());
if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(width, MeasureSpec.getSize(widthMeasureSpec));
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// Measure the TextureView
int width = getMeasuredWidth();
int height = getMeasuredHeight();
AspectRatio ratio = getAspectRatio();
if (mDisplayOrientationDetector.getLastKnownDisplayOrientation() % 180 == 0) {
ratio = ratio.inverse();
}
replacedert ratio != null;
if (height < width * ratio.getY() / ratio.getX()) {
mImpl.getView().measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(width * ratio.getY() / ratio.getX(), MeasureSpec.EXACTLY));
} else {
mImpl.getView().measure(MeasureSpec.makeMeasureSpec(height * ratio.getX() / ratio.getY(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
state.facing = getFacing();
state.ratio = getAspectRatio();
state.autoFocus = getAutoFocus();
state.flash = getFlash();
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setFacing(ss.facing);
setAspectRatio(ss.ratio);
setAutoFocus(ss.autoFocus);
setFlash(ss.flash);
}
/**
* Open a camera device and start showing camera preview. This is typically called from
* {@link Activity#onResume()}.
*/
public void start() {
if (!mImpl.start()) {
// store the state ,and restore this state after fall back o Camera1
Parcelable state = onSaveInstanceState();
// Camera2 uses legacy hardware layer; fall back to Camera1
mImpl = new Camera1(mCallbacks, createPreviewImpl(getContext()));
onRestoreInstanceState(state);
mImpl.start();
}
camera = camera1.getCamera();
}
/**
* Stop camera preview and close the device. This is typically called from
* {@link Activity#onPause()}.
*/
public void stop() {
mImpl.stop();
}
/**
* @return {@code true} if the camera is opened.
*/
public boolean isCameraOpened() {
return mImpl.isCameraOpened();
}
/**
* Add a new callback.
*
* @param callback The {@link Callback} to add.
* @see #removeCallback(Callback)
*/
public void addCallback(@NonNull Callback callback) {
mCallbacks.add(callback);
}
/**
* Remove a callback.
*
* @param callback The {@link Callback} to remove.
* @see #addCallback(Callback)
*/
public void removeCallback(@NonNull Callback callback) {
mCallbacks.remove(callback);
}
/**
* @param adjustViewBounds {@code true} if you want the CameraView to adjust its bounds to
* preserve the aspect ratio of camera.
* @see #getAdjustViewBounds()
*/
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (mAdjustViewBounds != adjustViewBounds) {
mAdjustViewBounds = adjustViewBounds;
requestLayout();
}
}
/**
* @return True when this CameraView is adjusting its bounds to preserve the aspect ratio of
* camera.
* @see #setAdjustViewBounds(boolean)
*/
public boolean getAdjustViewBounds() {
return mAdjustViewBounds;
}
/**
* Chooses camera by the direction it faces.
*
* @param facing The camera facing. Must be either {@link #FACING_BACK} or
* {@link #FACING_FRONT}.
*/
public void setFacing(@Facing int facing) {
mImpl.setFacing(facing);
}
/**
* Gets the direction that the current camera faces.
*
* @return The camera facing.
*/
@Facing
public int getFacing() {
// noinspection WrongConstant
return mImpl.getFacing();
}
/**
* Gets all the aspect ratios supported by the current camera.
*/
public Set<AspectRatio> getSupportedAspectRatios() {
return mImpl.getSupportedAspectRatios();
}
/**
* Sets the aspect ratio of camera.
*
* @param ratio The {@link AspectRatio} to be set.
*/
public void setAspectRatio(@NonNull AspectRatio ratio) {
if (mImpl.setAspectRatio(ratio)) {
requestLayout();
}
}
/**
* Gets the current aspect ratio of camera.
*
* @return The current {@link AspectRatio}. Can be {@code null} if no camera is opened yet.
*/
@Nullable
public AspectRatio getAspectRatio() {
return mImpl.getAspectRatio();
}
/**
* Enables or disables the continuous auto-focus mode. When the current camera doesn't support
* auto-focus, calling this method will be ignored.
*
* @param autoFocus {@code true} to enable continuous auto-focus mode. {@code false} to
* disable it.
*/
public void setAutoFocus(boolean autoFocus) {
mImpl.setAutoFocus(autoFocus);
}
/**
* Returns whether the continuous auto-focus mode is enabled.
*
* @return {@code true} if the continuous auto-focus mode is enabled. {@code false} if it is
* disabled, or if it is not supported by the current camera.
*/
public boolean getAutoFocus() {
return mImpl.getAutoFocus();
}
/**
* Sets the flash mode.
*
* @param flash The desired flash mode.
*/
public void setFlash(@Flash int flash) {
mImpl.setFlash(flash);
}
/**
* Gets the current flash mode.
*
* @return The current flash mode.
*/
@Flash
public int getFlash() {
// noinspection WrongConstant
return mImpl.getFlash();
}
/**
* Take a picture. The result will be returned to
* {@link Callback#onPictureTaken(RxCameraView, byte[])}.
*/
public void takePicture() {
mImpl.takePicture();
}
private clreplaced CallbackBridge implements CameraViewImpl.Callback {
private final ArrayList<Callback> mCallbacks = new ArrayList<>();
private boolean mRequestLayoutOnOpen;
CallbackBridge() {
}
public void add(Callback callback) {
mCallbacks.add(callback);
}
public void remove(Callback callback) {
mCallbacks.remove(callback);
}
@Override
public void onCameraOpened() {
if (mRequestLayoutOnOpen) {
mRequestLayoutOnOpen = false;
requestLayout();
}
for (Callback callback : mCallbacks) {
callback.onCameraOpened(RxCameraView.this);
}
}
@Override
public void onCameraClosed() {
for (Callback callback : mCallbacks) {
callback.onCameraClosed(RxCameraView.this);
}
}
@Override
public void onPictureTaken(byte[] data) {
for (Callback callback : mCallbacks) {
callback.onPictureTaken(RxCameraView.this, data);
}
}
public void reserveRequestLayoutOnOpen() {
mRequestLayoutOnOpen = true;
}
}
protected static clreplaced SavedState extends BaseSavedState {
@Facing
int facing;
AspectRatio ratio;
boolean autoFocus;
@Flash
int flash;
@SuppressWarnings("WrongConstant")
public SavedState(Parcel source, ClreplacedLoader loader) {
super(source);
facing = source.readInt();
ratio = source.readParcelable(loader);
autoFocus = source.readByte() != 0;
flash = source.readInt();
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(facing);
out.writeParcelable(ratio, 0);
out.writeByte((byte) (autoFocus ? 1 : 0));
out.writeInt(flash);
}
public static final Parcelable.Creator<SavedState> CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClreplacedLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
});
}
/**
* Callback for monitoring events about {@link RxCameraView}.
*/
@SuppressWarnings("UnusedParameters")
public abstract static clreplaced Callback {
/**
* Called when camera is opened.
*
* @param rxCameraView The replacedociated {@link RxCameraView}.
*/
public void onCameraOpened(RxCameraView rxCameraView) {
}
/**
* Called when camera is closed.
*
* @param rxCameraView The replacedociated {@link RxCameraView}.
*/
public void onCameraClosed(RxCameraView rxCameraView) {
}
/**
* Called when a picture is taken.
*
* @param rxCameraView The replacedociated {@link RxCameraView}.
* @param data JPEG data.
*/
public void onPictureTaken(RxCameraView rxCameraView, byte[] data) {
}
}
private float oldDist = 1f;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount() == 1) {
if (camera != null) {
/*camera.startPreview();
handleFocusMetering(event, camera);*/
}
} else {
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = getFingerSpacing(event);
break;
case MotionEvent.ACTION_MOVE:
float newDist = getFingerSpacing(event);
if (newDist > oldDist) {
Log.e("Camera", "进入放大手势");
handleZoom(true, camera);
} else if (newDist < oldDist) {
Log.e("Camera", "进入缩小手势");
handleZoom(false, camera);
}
oldDist = newDist;
break;
default:
break;
}
}
return true;
}
private void handleZoom(boolean isZoomIn, Camera camera) {
Log.e("Camera", "进入缩小放大方法");
Camera.Parameters params = camera.getParameters();
if (params.isZoomSupported()) {
int maxZoom = params.getMaxZoom();
int zoom = params.getZoom();
if (isZoomIn && zoom < maxZoom) {
Log.e("Camera", "进入放大方法zoom=" + zoom);
zoom++;
} else if (zoom > 0) {
Log.e("Camera", "进入缩小方法zoom=" + zoom);
zoom--;
}
params.setZoom(zoom);
camera.setParameters(params);
} else {
Log.i(TAG, "zoom not supported");
}
}
private static void handleFocusMetering(MotionEvent event, Camera camera) {
Log.e("Camera", "进入handleFocusMetering");
Camera.Parameters params = camera.getParameters();
Camera.Size previewSize = params.getPreviewSize();
Rect focusRect = calculateTapArea(event.getX(), event.getY(), 1f, previewSize);
Rect meteringRect = calculateTapArea(event.getX(), event.getY(), 1.5f, previewSize);
camera.cancelAutoFocus();
if (params.getMaxNumFocusAreas() > 0) {
List<Camera.Area> focusAreas = new ArrayList<>();
focusAreas.add(new Camera.Area(focusRect, 800));
params.setFocusAreas(focusAreas);
} else {
Log.i(TAG, "focus areas not supported");
}
if (params.getMaxNumMeteringAreas() > 0) {
List<Camera.Area> meteringAreas = new ArrayList<>();
meteringAreas.add(new Camera.Area(meteringRect, 800));
params.setMeteringAreas(meteringAreas);
} else {
Log.i(TAG, "metering areas not supported");
}
final String currentFocusMode = params.getFocusMode();
params.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
camera.setParameters(params);
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
Camera.Parameters params = camera.getParameters();
params.setFocusMode(currentFocusMode);
camera.setParameters(params);
}
});
}
private static float getFingerSpacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
Log.e("Camera", "getFingerSpacing ,计算距离 = " + (float) Math.sqrt(x * x + y * y));
return (float) Math.sqrt(x * x + y * y);
}
private static Rect calculateTapArea(float x, float y, float coefficient, Camera.Size previewSize) {
float focusAreaSize = 300;
int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue();
int centerX = (int) (x / previewSize.width - 1000);
int centerY = (int) (y / previewSize.height - 1000);
int left = clamp(centerX - areaSize / 2, -1000, 1000);
int top = clamp(centerY - areaSize / 2, -1000, 1000);
RectF rectF = new RectF(left, top, left + areaSize, top + areaSize);
return new Rect(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF.bottom));
}
private static int clamp(int x, int min, int max) {
if (x > max) {
return max;
}
if (x < min) {
return min;
}
return x;
}
}
19
Source : CameraPreview.java
with Apache License 2.0
from starscryer
with Apache License 2.0
from starscryer
/**
* Starts the camera preview on the current surface. Abstracts out the differences in API
* from the CameraManager
*
* @throws IOException Which is caught by the CameraManager to display an error
*/
public void startPreview(final Camera camera) throws IOException {
mHost.startPreview(camera);
}
19
Source : CameraManager.java
with Apache License 2.0
from starscryer
with Apache License 2.0
from starscryer
/**
* Sets the current camera, releasing any previously opened camera
*/
private void setCamera(final Camera camera) {
if (mCamera == camera) {
return;
}
releaseMediaRecorder(true);
releaseCamera(mCamera);
mCamera = camera;
tryShowPreview();
if (mListener != null) {
mListener.onCameraChanged();
}
}
19
Source : CameraManager.java
with Apache License 2.0
from starscryer
with Apache License 2.0
from starscryer
/**
* Asynchronously releases a camera
*
* @param camera The camera to release
*/
private void releaseCamera(final Camera camera) {
if (camera == null) {
return;
}
mFocusOverlayManager.onCameraReleased();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... params) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Releasing camera " + mCameraIndex);
}
sCameraWrapper.release(camera);
return null;
}
}.execute();
}
19
Source : TakeVideoActivity.java
with Apache License 2.0
from smartyuge
with Apache License 2.0
from smartyuge
private void setDispaly(Camera.Parameters parameters, Camera camera) {
if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
setDisplayOrientation(camera, 90);
} else {
parameters.setRotation(90);
}
}
19
Source : FroyoLedFlashlight.java
with MIT License
from SDRausty
with MIT License
from SDRausty
public clreplaced FroyoLedFlashlight implements Flashlight {
private static final String TAG = "qs.floyoled";
private static final String MODE_TORCH = Camera.Parameters.FLASH_MODE_TORCH;
private static final String MODE_OFF = Camera.Parameters.FLASH_MODE_OFF;
private Camera mCamera;
public boolean isOn(Context context) {
return mCamera != null && MODE_TORCH.equals(mCamera.getParameters().getFlashMode());
}
public boolean isSupported(Context context) {
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
Camera camera = null;
try {
camera = Camera.open();
return sdkVersion >= 8 && /*froyo*/
camera.getParameters().getFlashMode() != null;
/*flash is supported*/
} catch (Exception e) {
Log.e(TAG, "isSupported", e);
return false;
} finally {
if (camera != null) {
camera.release();
}
}
}
public void setOn(boolean on, Context context) {
Camera camera = mCamera;
if (on) {
if (camera == null) {
mCamera = camera = Camera.open();
camera.startPreview();
}
Parameters params = camera.getParameters();
params.setFlashMode(MODE_TORCH);
camera.setParameters(params);
} else {
if (camera != null) {
try {
Parameters params = camera.getParameters();
params.setFlashMode(MODE_OFF);
camera.setParameters(params);
} finally {
camera.release();
mCamera = null;
}
}
}
}
public int getType() {
return TYPE_FROYO;
}
}
19
Source : CameraManager.java
with MIT License
from safaeean
with MIT License
from safaeean
public clreplaced CameraManager {
private int mCameraId = -1;
private Camera mCamera;
public CameraManager() {
mCamera = getCameraInstance();
}
public Camera getCamera() {
if (mCamera == null) {
mCamera = getCameraInstance();
}
return mCamera;
}
public Camera getCamera(String cameraType) {
if (mCamera == null) {
mCamera = getCameraInstance(cameraType);
}
return mCamera;
}
public void releaseCamera() {
if (mCamera != null) {
// release the camera for other applications
mCamera.release();
mCamera = null;
}
}
public Camera getCameraInstance() {
return getCameraInstance(-1);
}
public Camera getCameraInstance(String cameraType) {
mCameraId = -1;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int cameraId = 0; cameraId < Camera.getNumberOfCameras(); cameraId++) {
Camera.getCameraInfo(cameraId, cameraInfo);
if (cameraType.equals("back") && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
mCameraId = cameraId;
break;
}
if (cameraType.equals("front") && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
mCameraId = cameraId;
break;
}
}
return getCameraInstance(mCameraId);
}
// A safe way to get an instance of the Camera object.
public Camera getCameraInstance(int cameraId) {
Camera c = null;
try {
if (cameraId == -1) {
// attempt to get a Camera instance
c = Camera.open();
} else {
// attempt to get a Camera instance
c = Camera.open(cameraId);
}
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
public boolean isFlashSupported(Camera camera) {
// Credits: Top answer at http://stackoverflow.com/a/19599365/868173
if (camera != null) {
Camera.Parameters parameters = camera.getParameters();
if (parameters.getFlashMode() == null) {
return false;
}
List<String> supportedFlashModes = parameters.getSupportedFlashModes();
if (supportedFlashModes == null || supportedFlashModes.isEmpty() || supportedFlashModes.size() == 1 && supportedFlashModes.get(0).equals(Camera.Parameters.FLASH_MODE_OFF)) {
return false;
}
} else {
return false;
}
return true;
}
}
19
Source : CameraManager.java
with MIT License
from safaeean
with MIT License
from safaeean
// A safe way to get an instance of the Camera object.
public Camera getCameraInstance(int cameraId) {
Camera c = null;
try {
if (cameraId == -1) {
// attempt to get a Camera instance
c = Camera.open();
} else {
// attempt to get a Camera instance
c = Camera.open(cameraId);
}
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
19
Source : Camera1Preview.java
with Apache License 2.0
from rome753
with Apache License 2.0
from rome753
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
19
Source : Camera1Preview.java
with Apache License 2.0
from rome753
with Apache License 2.0
from rome753
public void switchCamera(Camera camera) {
// setCamera(camera);
// try {
// camera.setPreviewDisplay(mHolder);
// } catch (IOException exception) {
// Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
// }
// Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
// requestLayout();
//
// camera.setParameters(parameters);
}
19
Source : CameraUtil.java
with MIT License
from roadrover
with MIT License
from roadrover
/**
* Camera工具类,用来适配不同平台的Camera
*/
public clreplaced CameraUtil {
// ATC平台摄像头对象
private ATCCamera mATCCamera;
// 标准的摄像头接口
private Camera mCamera;
/**
* 创建一个CameraUtil对象
*/
public static CameraUtil open(int cameraId, Context context) {
return new CameraUtil(cameraId, context);
}
/**
* 判断是否是ATC平台
* @return
*/
public static boolean isATCPlatform() {
return ATCCamera.detectionIsATCPlatform();
}
/**
* 是否是ATC摄像头被打开
* @return
*/
public boolean isATCCamera() {
return mATCCamera != null;
}
/**
* 获取视频信号
* @return
*/
public int getVideoSignal() {
if (mATCCamera != null) {
return mATCCamera.getVideoSignal();
}
return IVIAVIn.Signal.UNSTABLE_SIGNAL;
}
private CameraUtil(int cameraId, Context context) {
if (ATCCamera.detectionIsATCPlatform()) {
mATCCamera = ATCCamera.open(cameraId, context);
} else {
mCamera = Camera.open(cameraId);
}
}
/**
* 设置视频监听回调
* @param listener
*/
public void setAVInCallback(IVIAVIn.AVInListener listener) {
if (mATCCamera != null) {
// ATC平台需要通过该方法返回当前信号状态
mATCCamera.setAVInCallback(listener);
}
}
/**
* 初始化摄像头参数
* @param avId 设置参数id
* @param brightness 亮度
* @param contrast 对比度
* @param saturation 饱和度
*/
public void initVideoParam(int avId, VideoParam brightness, VideoParam contrast, VideoParam saturation) {
if (mATCCamera != null) {
// atc 平台需要在UI起来之前,先刷一遍参数
if (brightness != null) {
mATCCamera.setParam(VideoParam.makeId(avId, VideoParam.SubId.BRIGHTNESS), brightness.mValue);
}
if (contrast != null) {
mATCCamera.setParam(VideoParam.makeId(avId, VideoParam.SubId.CONTRAST), contrast.mValue);
}
if (saturation != null) {
mATCCamera.setParam(VideoParam.makeId(avId, VideoParam.SubId.SATURATION), saturation.mValue);
}
}
}
/**
* Returns the current settings for this Camera service. </br>
* ATC平台不需要该方法
*/
public Camera.Parameters getParameters() {
if (mCamera != null) {
return mCamera.getParameters();
}
return null;
}
/**
* Changes the settings for this Camera service. </br>
* ATC平台不需要该方法
*/
public void setParameters(Camera.Parameters params) {
if (mCamera != null) {
mCamera.setParameters(params);
}
}
/**
* 释放适配
*/
public final void release() {
if (mATCCamera != null) {
mATCCamera.release();
} else if (mCamera != null) {
mCamera.release();
}
}
/**
* Starts capturing and drawing preview frames to the screen.
* Preview will not actually start until a surface is supplied
*/
public void startPreview() {
if (mATCCamera != null) {
mATCCamera.startPreview();
} else if (mCamera != null) {
mCamera.startPreview();
}
}
/**
* Stops capturing and drawing preview frames to the surface, and
* resets the camera for a future call to {@link #startPreview()}.
*/
public final void stopPreview() {
if (mATCCamera != null) {
mATCCamera.stopPreview();
} else if (mCamera != null) {
mCamera.stopPreview();
}
}
/**
* Sets the {@link Surface} to be used for live preview.
* Either a surface or surface texture is necessary for preview, and
* preview is necessary to take pictures. The same surface can be re-set
* without harm. Setting a preview surface will un-set any preview surface
* texture that was set via .
*/
public final void setPreviewDisplay(SurfaceHolder holder) throws IOException {
if (mATCCamera != null) {
mATCCamera.setPreviewDisplay(holder);
} else if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
}
/**
* 设置ATC摄像头视频参数
* @param id
* @param value
*/
public void setATCCameraParam(int id, int value) {
if (mATCCamera != null) {
mATCCamera.setParam(id, value);
}
}
/**
* 获取ATC摄像头的视频参数
* @param id
* @return
*/
public int getATCCameraParam(int id) {
if (mATCCamera != null) {
return mATCCamera.getParamValue(id);
}
return 0;
}
}
19
Source : CameraPreview.java
with Apache License 2.0
from ricohapi
with Apache License 2.0
from ricohapi
/**
* Preview camera image
*/
public clreplaced CameraPreview {
private Camera mCamera;
private int mCameraId;
private Camera.Parameters mParameters;
/**
* Constructor
*/
public CameraPreview() {
}
/**
* Start preview
* @param surfaceTexture Surface texture
*/
public void start(SurfaceTexture surfaceTexture) {
if (mCamera == null) {
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
mCameraId = i;
}
try {
mCamera = Camera.open(mCameraId);
} catch (Exception e) {
Timber.d(e.getMessage());
}
}
mCamera.setErrorCallback(mErrorCallback);
mParameters = mCamera.getParameters();
mParameters.setPreviewSize(1920, 960);
mParameters.set("RIC_SHOOTING_MODE", "RicStillPreview1920");
mParameters.set("RIC_PROC_SreplacedCHING", "RicStaticSreplacedching");
mParameters.set("recording-hint", "false");
mCamera.setParameters(mParameters);
mCamera.setDisplayOrientation(0);
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException e) {
Timber.d(e.getMessage());
}
mCamera.startPreview();
}
}
/**
* Stop preview
*/
public void stop() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.setErrorCallback(null);
mCamera.release();
mCamera = null;
mParameters = null;
}
}
private Camera.ErrorCallback mErrorCallback = new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
String cameraError = String.format("Camera error. error=%d", error);
Timber.e(cameraError);
throw new RuntimeException(cameraError);
}
};
}
19
Source : CameraManager.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* 来自网络copy
*
* 作者: 陈涛
*
* 日期: 2014年8月20日
*
* 描述: 该类主要负责对相机的操作
*/
public final clreplaced CameraManager {
private static final String TAG = "CameraManager";
private final CameraConfigurationManager configManager;
private Camera camera;
private boolean initialized;
public CameraManager(Context context) {
this.configManager = new CameraConfigurationManager(context);
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @throws IOException
* Indicates the camera driver failed to open.
*/
public synchronized void openDriver() throws IOException {
Camera theCamera = camera;
if (theCamera == null) {
theCamera = Camera.open();
if (theCamera == null) {
throw new IOException();
}
camera = theCamera;
}
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(theCamera);
}
Camera.Parameters parameters = theCamera.getParameters();
// Save
String parametersFlattened = parameters == null ? null : parameters.flatten();
// these,
// temporarily
try {
configManager.setDesiredCameraParameters(theCamera, false);
} catch (RuntimeException re) {
// Driver failed
LogUtil.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters");
LogUtil.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
LogUtil.w(TAG, "Camera rejected even safe-mode parameters! No configuration");
}
}
}
}
public synchronized boolean isOpen() {
return camera != null;
}
public Camera getCamera() {
return camera;
}
/**
* Closes the camera driver if still in use.
*/
public synchronized void closeDriver() {
if (camera != null) {
camera.release();
camera = null;
}
}
/**
* 获取相机分辨率
*
* @return
*/
public Point getCameraResolution() {
return configManager.getCameraResolution();
}
}
19
Source : CameraView.java
with Apache License 2.0
from protyposis
with Apache License 2.0
from protyposis
/**
* @author Mario Guggenberger
*/
public clreplaced CameraView extends SpectaculumView {
private static final String TAG = CameraView.clreplaced.getSimpleName();
private Camera mCamera;
private int mCameraId;
public CameraView(Context context) {
super(context);
init(context);
}
public CameraView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mCameraId = 0;
if (!checkCameraHardware(context)) {
Log.w(TAG, "no camera present");
}
}
/**
* Check if this device has a camera
*/
private boolean checkCameraHardware(Context context) {
if (isInEditMode()) {
// there's no camera in the layout editor available
return false;
}
if (context.getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
@Override
public void onInputSurfaceCreated(InputSurfaceHolder inputSurfaceHolder) {
startCamera();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
stopCamera();
super.surfaceDestroyed(holder);
}
@Override
public void onPause() {
stopCamera();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
private void startCamera() {
try {
if (mCamera == null) {
mCamera = Camera.open(mCameraId);
// enable autofocus if available
List<String> supportedFocusModes = mCamera.getParameters().getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
Camera.Parameters params = mCamera.getParameters();
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
mCamera.setParameters(params);
}
// set orientation
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(mCameraId, info);
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
int rotation = windowManager.getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees + 360) % 360;
}
mCamera.setDisplayOrientation(result);
// setup preview
mCamera.setPreviewTexture(getInputHolder().getSurfaceTexture());
mCamera.startPreview();
int width, height;
if (result == 0 || result == 180) {
width = mCamera.getParameters().getPreviewSize().width;
height = mCamera.getParameters().getPreviewSize().height;
} else {
// swap width/height in portrait mode for a correct aspect ratio
height = mCamera.getParameters().getPreviewSize().width;
width = mCamera.getParameters().getPreviewSize().height;
}
updateResolution(width, height);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public boolean supportsCameraSwitch() {
return Camera.getNumberOfCameras() > 1;
}
public void switchCamera() {
mCameraId = ((mCameraId + 1) % Camera.getNumberOfCameras());
stopCamera();
startCamera();
}
}
19
Source : CameraActivity.java
with Apache License 2.0
from pop1234o
with Apache License 2.0
from pop1234o
/**
* A safe way to get an instance of the Camera object.
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
19
Source : DefaultEasyCamera.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
/**
* The default implementation of EasyCamera
*/
public clreplaced DefaultEasyCamera implements EasyCamera {
private Camera camera;
private int id;
/**
* Gets access to the default camera
* See <a href="http://developer.android.com/reference/android/hardware/Camera.html#open%28%29">Camera.open()</a>
*/
public static final EasyCamera open() {
return new DefaultEasyCamera(Camera.open(), 0);
}
/**
* Gets access to a specific camera
* See <a href="http://developer.android.com/reference/android/hardware/Camera.html#open%28int%29">Camera.open(..)</a>
*/
public static final EasyCamera open(int id) {
return new DefaultEasyCamera(Camera.open(id), id);
}
private DefaultEasyCamera(Camera camera, int id) {
this.camera = camera;
this.id = id;
}
@Override
public CameraActions startPreview(SurfaceHolder holder) throws IOException {
if (holder == null) {
throw new NullPointerException("You cannot start preview without a preview surface");
}
camera.setPreviewDisplay(holder);
camera.startPreview();
return new DefaultCameraActions(this);
}
@Override
public CameraActions startPreview(SurfaceTexture texture) throws IOException {
if (texture == null) {
throw new NullPointerException("You cannot start preview without a preview texture");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
camera.setPreviewTexture(texture);
} else {
throw new IllegalStateException("Your Android version does not support this method.");
}
camera.startPreview();
return new DefaultCameraActions(this);
}
@Override
public void close() {
camera.release();
}
@Override
public void unlock() {
camera.unlock();
}
@Override
public void lock() {
camera.lock();
}
@Override
public void reconnect() throws IOException {
camera.reconnect();
}
@Override
public void stopPreview() {
camera.stopPreview();
}
@Override
public void setPreviewCallback(Camera.PreviewCallback cb) {
camera.setPreviewCallback(cb);
}
@Override
public void setOneShotPreviewCallback(Camera.PreviewCallback cb) {
camera.setOneShotPreviewCallback(cb);
}
@Override
public void setPreviewCallbackWithBuffer(Camera.PreviewCallback cb) {
camera.setPreviewCallbackWithBuffer(cb);
}
@Override
public void addCallbackBuffer(byte[] callbackBuffer) {
camera.addCallbackBuffer(callbackBuffer);
}
@Override
public void autoFocus(Camera.AutoFocusCallback cb) {
camera.autoFocus(cb);
}
@Override
public void cancelAutoFocus() {
camera.cancelAutoFocus();
}
@Override
public void startSmoothZoom(int value) {
camera.startSmoothZoom(value);
}
@Override
public void stopSmoothZoom() {
camera.stopSmoothZoom();
}
@Override
public void setDisplayOrientation(int degrees) {
camera.setDisplayOrientation(degrees);
}
@Override
public void setZoomChangeListener(Camera.OnZoomChangeListener listener) {
camera.setZoomChangeListener(listener);
}
@Override
public void setErrorCallback(Camera.ErrorCallback cb) {
camera.setErrorCallback(cb);
}
@Override
public void setParameters(Camera.Parameters parameters) {
camera.setParameters(parameters);
}
@Override
public Camera.Parameters getParameters() {
return camera.getParameters();
}
@Override
public Camera getRawCamera() {
return camera;
}
@Override
public void alignCameraAndDisplayOrientation(WindowManager windowManager) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
int rotation = windowManager.getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
// compensate the mirror
result = (360 - result) % 360;
} else {
// back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
@Override
public boolean enableShutterSound(boolean enabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return camera.enableShutterSound(enabled);
}
return false;
}
@Override
public void setAutoFocusMoveCallback(AutoFocusMoveCallback cb) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
camera.setAutoFocusMoveCallback(cb);
}
}
@Override
public void setFaceDetectionListener(FaceDetectionListener listener) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
camera.setFaceDetectionListener(listener);
}
}
@Override
public void startFaceDetection() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
camera.startFaceDetection();
}
}
@Override
public void stopFaceDetection() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
camera.stopFaceDetection();
}
}
}
19
Source : OpenCamera.java
with Apache License 2.0
from MRYangY
with Apache License 2.0
from MRYangY
/**
* Created by yangyu on 17/10/18.
*/
public final clreplaced OpenCamera {
private final int index;
private final Camera camera;
private final CameraFacing facing;
private final int orientation;
public OpenCamera(int index, Camera camera, CameraFacing facing, int orientation) {
this.index = index;
this.camera = camera;
this.facing = facing;
this.orientation = orientation;
}
public Camera getCamera() {
return camera;
}
public CameraFacing getFacing() {
return facing;
}
public int getOrientation() {
return orientation;
}
@Override
public String toString() {
return "Camera #" + index + " : " + facing + ',' + orientation;
}
}
19
Source : CameraManager.java
with Apache License 2.0
from luocheng1111
with Apache License 2.0
from luocheng1111
/**
* This object wraps the Camera service object and expects to be the only one talking to it. The
* implementation encapsulates the steps needed to take preview-sized images, which are used for
* both preview and decoding.
*
* @author [email protected] (Daniel Switkin)
*/
public final clreplaced CameraManager {
private static final String TAG = CameraManager.clreplaced.getSimpleName();
private final CameraConfigurationManager configManager;
private Camera camera;
private AutoFocusManager autoFocusManager;
private boolean initialized;
private boolean previewing;
private int requestedCameraId = OpenCameraInterface.NO_REQUESTED_CAMERA;
/**
* Preview frames are delivered here, which we preplaced on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final PreviewCallback previewCallback;
public CameraManager(Context context) {
this.configManager = new CameraConfigurationManager(context);
previewCallback = new PreviewCallback(configManager);
}
/**
* 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) {
theCamera = OpenCameraInterface.open(requestedCameraId);
if (theCamera == null) {
throw new IOException();
}
camera = theCamera;
}
theCamera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(theCamera);
}
Camera.Parameters parameters = theCamera.getParameters();
// Save these, temporarily
String parametersFlattened = parameters == null ? null : parameters.flatten();
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");
}
}
}
}
public synchronized boolean isOpen() {
return camera != null;
}
/**
* Closes the camera driver if still in use.
*/
public synchronized void closeDriver() {
if (camera != null) {
camera.release();
camera = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public synchronized void startPreview() {
Camera theCamera = camera;
if (theCamera != null && !previewing) {
theCamera.startPreview();
previewing = true;
autoFocusManager = new AutoFocusManager(camera);
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public synchronized void stopPreview() {
if (autoFocusManager != null) {
autoFocusManager.stop();
autoFocusManager = null;
}
if (camera != null && previewing) {
camera.stopPreview();
previewCallback.setHandler(null, 0);
previewing = false;
}
}
public synchronized void setTorch(boolean newSetting) {
if (newSetting != configManager.getTorchState(camera)) {
if (camera != null) {
if (autoFocusManager != null) {
autoFocusManager.stop();
}
configManager.setTorch(camera, newSetting);
if (autoFocusManager != null) {
autoFocusManager.start();
}
}
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public synchronized void requestPreviewFrame(Handler handler, int message) {
Camera theCamera = camera;
if (theCamera != null && previewing) {
previewCallback.setHandler(handler, message);
theCamera.setOneShotPreviewCallback(previewCallback);
}
}
/**
* Allows third party apps to specify the camera ID, rather than determine
* it automatically based on available cameras and their orientation.
*
* @param cameraId camera ID of the camera to use. A negative value means "no preference".
*/
public synchronized void setManualCameraId(int cameraId) {
requestedCameraId = cameraId;
}
public Camera.Size getPreviewSize() {
if (null != camera) {
return camera.getParameters().getPreviewSize();
}
return null;
}
public Point getCameraResolution() {
return configManager.getCameraResolution();
}
}
19
Source : OpenCamera.java
with Apache License 2.0
from kangdp
with Apache License 2.0
from kangdp
public final clreplaced OpenCamera {
private final int index;
private final Camera camera;
private final CameraFacing facing;
private final int orientation;
OpenCamera(int index, Camera camera, CameraFacing facing, int orientation) {
this.index = index;
this.camera = camera;
this.facing = facing;
this.orientation = orientation;
}
public Camera getCamera() {
return camera;
}
public CameraFacing getFacing() {
return facing;
}
public int getOrientation() {
return orientation;
}
@Override
public String toString() {
return "Camera #" + index + " : " + facing + ',' + orientation;
}
}
19
Source : EntropyGatherActivity.java
with MIT License
from kalaspuffar
with MIT License
from kalaspuffar
/**
* A safe way to get an instance of the Camera object.
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
19
Source : MotionDetector.java
with Apache License 2.0
from jjoe64
with Apache License 2.0
from jjoe64
private Camera getCameraInstance() {
Camera c = null;
try {
if (Camera.getNumberOfCameras() >= 2) {
// if you want to open front facing camera use this line
c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
} else {
c = Camera.open();
}
} catch (Exception e) {
// Camera is not available (in use or does not exist)
// txtStatus.setText("Kamera nicht zur Benutzung freigegeben");
}
// returns null if camera is unavailable
return c;
}
See More Examples