在應用軟件開發中,圖片數據,對於一個公司來說是十分重要的,例如:上傳圖片資料,修改用戶頭像等,而這其中就離不開相機和相冊的使用。對於ios平臺來說,直接調用系統相機或相冊,就可搞定一切。然而對於Android平臺來說,直接調用系統相機或相冊,在適配和體驗上問題比較多,具體原因,相比大家也知道,安卓品牌太多太雜,性能不一。鑑於此,在開發的過程中,遇到類似問題,建議自己實現相機或相冊功能,以保證體驗完整。本篇博文將會重點介紹Camera相機的實現。
首先,推薦兩個github項目,可以直接使用的相機和相冊;另外,也推薦一個聯繫人選擇器:
一、打開Camera
try {
mCamera = Camera.open();//開啓相機
} catch (RuntimeException e) {
e.printStackTrace();
LogUtil.d(TAG, "攝像頭異常,請檢查攝像頭權限是否應許");
ToastUtil.getInstance().toast("攝像頭異常,請檢查攝像頭權限是否應許");
return;
}
二、設置Camera參數
默認尺寸可以自由設置,這裏取手機的分辨率爲默認尺寸。
1.根據指定分辨率查找相機最佳適配分辨率並設置
private void setCameraParams(int width, int height) {
LogUtil.i(TAG, "setCameraParams width=" + width + " height=" + height);
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> pictureSizeList = parameters.getSupportedPictureSizes();
sort(pictureSizeList);//排序
for (Camera.Size size : pictureSizeList) {
LogUtil.i(TAG, "攝像頭支持的分辨率:" + " size.width=" + size.width + " size.height=" + size.height);
}
Camera.Size picSize = getBestSupportedSize(pictureSizeList, ((float) height / width));//從列表中選取合適的分辨率
if (null == picSize) {
picSize = parameters.getPictureSize();
}
LogUtil.e(TAG, "我們選擇的攝像頭分辨率:" + "picSize.width=" + picSize.width + " picSize.height=" + picSize.height);
// 根據選出的PictureSize重新設置SurfaceView大小
parameters.setPictureSize(picSize.width, picSize.height);
....
2.根據指定分辨率查找相機最佳預覽分辨率並設置
private void setCameraParams(int width, int height) {
LogUtil.i(TAG, "setCameraParams width=" + width + " height=" + height);
Camera.Parameters parameters = mCamera.getParameters();
/*************************** 獲取攝像頭支持的PreviewSize列表********************/
List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
sort(previewSizeList);
for (Camera.Size size : previewSizeList) {
LogUtil.i(TAG, "攝像支持可預覽的分辨率:" + " size.width=" + size.width + " size.height=" + size.height);
}
Camera.Size preSize = getBestSupportedSize(previewSizeList, ((float) height) / width);
if (null != preSize) {
LogUtil.e(TAG, "我們選擇的預覽分辨率:" + "preSize.width=" + preSize.width + " preSize.height=" + preSize.height);
parameters.setPreviewSize(preSize.width, preSize.height);
}
......
3.最佳分辨率適配算法(先排序)
/**
* 如包含默認尺寸,則選默認尺寸,如沒有,則選最大的尺寸
* 規則:在相同比例下,1.優先尋找長寬分辨率相同的->2.找長寬有一個相同的分辨率->3.找最大的分辨率
*
* @param sizes 尺寸集合
* @return 返回合適的尺寸
*/
private Camera.Size getBestSupportedSize(List<Camera.Size> sizes, float screenRatio) {
Camera.Size largestSize = null;
int largestArea = 0;
for (Camera.Size size : sizes) {
if ((float) size.height / (float) size.width == screenRatio) {
if (size.width == DEFAULT_PHOTO_WIDTH && size.height == DEFAULT_PHOTO_HEIGHT) {
// 包含特定的尺寸,直接取該尺寸
largestSize = size;
break;
} else if (size.height == DEFAULT_PHOTO_HEIGHT || size.width == DEFAULT_PHOTO_WIDTH) {
largestSize = size;
break;
}
int area = size.height + size.width;
if (area > largestArea) {//找出最大的合適尺寸
largestArea = area;
largestSize = size;
}
} else if (size.height == DEFAULT_PHOTO_HEIGHT || size.width == DEFAULT_PHOTO_WIDTH) {
largestSize = size;
break;
}
}
if (largestSize == null) {
largestSize = sizes.get(sizes.size() - 1);
}
return largestSize;
}
4.對焦模式選擇
由於部分智能手機,前置攝像頭無對焦模式,對焦參數設置應區分前置攝像頭
//對焦模式的選擇
if(cameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);//手動區域自動對焦
}
5.圖片質量
PixelFormat中有多種模式,源碼有解。
//圖片質量
parameters.setJpegQuality(100); // 設置照片質量
parameters.setPreviewFormat(PixelFormat.YCbCr_420_SP); // 預覽格式
parameters.setPictureFormat(PixelFormat.JPEG); // 相片格式爲JPEG,默認爲NV21
6.閃關燈及橫豎屏鏡頭調整
// 關閃光燈
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
// 橫豎屏鏡頭自動調整
if (mContext.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
mCamera.setDisplayOrientation(90);
} else {
mCamera.setDisplayOrientation(0);
}
7.相機異常監聽
//相機異常監聽
mCamera.setErrorCallback(new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
String error_str;
switch (error) {
case Camera.CAMERA_ERROR_SERVER_DIED: // 攝像頭已損壞
error_str = "攝像頭已損壞";
break;
case Camera.CAMERA_ERROR_UNKNOWN:
error_str = "攝像頭異常,請檢查攝像頭權限是否應許";
break;
default:
error_str = "攝像頭異常,請檢查攝像頭權限是否應許";
break;
}
ToastUtil.getInstance().toast(error_str);
Log.i(TAG, error_str);
}
});
完整參數設置代碼:
/**
* 設置分辨率等參數
*
* @param width 寬
* @param height 高
*/
private void setCameraParams(int width, int height) {
LogUtil.i(TAG, "setCameraParams width=" + width + " height=" + height);
Camera.Parameters parameters = mCamera.getParameters();
/*************************** 獲取攝像頭支持的PictureSize列表********************/
List<Camera.Size> pictureSizeList = parameters.getSupportedPictureSizes();
sort(pictureSizeList);//排序
for (Camera.Size size : pictureSizeList) {
LogUtil.i(TAG, "攝像頭支持的分辨率:" + " size.width=" + size.width + " size.height=" + size.height);
}
Camera.Size picSize = getBestSupportedSize(pictureSizeList, ((float) height / width));//從列表中選取合適的分辨率
if (null == picSize) {
picSize = parameters.getPictureSize();
}
LogUtil.e(TAG, "我們選擇的攝像頭分辨率:" + "picSize.width=" + picSize.width + " picSize.height=" + picSize.height);
// 根據選出的PictureSize重新設置SurfaceView大小
parameters.setPictureSize(picSize.width, picSize.height);
/*************************** 獲取攝像頭支持的PreviewSize列表********************/
List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
sort(previewSizeList);
for (Camera.Size size : previewSizeList) {
LogUtil.i(TAG, "攝像支持可預覽的分辨率:" + " size.width=" + size.width + " size.height=" + size.height);
}
Camera.Size preSize = getBestSupportedSize(previewSizeList, ((float) height) / width);
if (null != preSize) {
LogUtil.e(TAG, "我們選擇的預覽分辨率:" + "preSize.width=" + preSize.width + " preSize.height=" + preSize.height);
parameters.setPreviewSize(preSize.width, preSize.height);
}
/*************************** 對焦模式的選擇 ********************/
if(cameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);//手動區域自動對焦
}
//圖片質量
parameters.setJpegQuality(100); // 設置照片質量
parameters.setPreviewFormat(PixelFormat.YCbCr_420_SP); // 預覽格式
parameters.setPictureFormat(PixelFormat.JPEG); // 相片格式爲JPEG,默認爲NV21
// 關閃光燈
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
// 橫豎屏鏡頭自動調整
if (mContext.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
mCamera.setDisplayOrientation(90);
} else {
mCamera.setDisplayOrientation(0);
}
//相機異常監聽
mCamera.setErrorCallback(new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
String error_str;
switch (error) {
case Camera.CAMERA_ERROR_SERVER_DIED: // 攝像頭已損壞
error_str = "攝像頭已損壞";
break;
case Camera.CAMERA_ERROR_UNKNOWN:
error_str = "攝像頭異常,請檢查攝像頭權限是否應許";
break;
default:
error_str = "攝像頭異常,請檢查攝像頭權限是否應許";
break;
}
ToastUtil.getInstance().toast(error_str);
Log.i(TAG, error_str);
}
});
mCamera.cancelAutoFocus();
mCamera.setParameters(parameters);
}
三、對焦
要實現點擊對焦,並有對焦環,需要自定義實現對焦環View.
1.自定義對焦環View-CameraFocusView
核心功能,就是對焦環縮小,並變綠。利用動畫改變對焦環半徑即可。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(isShow){
if(radius == GREEN_RADIUS){
mPaint.setColor(Color.GREEN);
}
if(centerPoint!=null){
canvas.drawCircle(centerPoint.x, centerPoint.y, radius, mPaint);
}
}
}
private void showAnimView() {
isShow = true;
if (lineAnimator == null) {
lineAnimator = ValueAnimator.ofInt(0, 20);
lineAnimator.setDuration(DURATION_TIME);
lineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int animationValue = (Integer) animation
.getAnimatedValue();
if(lastValue!=animationValue&&radius>=(int) ((mScreenWidth * 0.1)-20)){
radius = radius - animationValue;
lastValue = animationValue;
}
isShow = true;
invalidate();
}
});
lineAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
isShow = false;
lastValue = 0;
mPaint.setColor(Color.WHITE);
radius = (int) (mScreenWidth * 0.1);
invalidate();
}
});
}else{
lineAnimator.end();
lineAnimator.cancel();
lineAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
lineAnimator.start();
}
}
2.佈局界面
讓對焦環自定義View獲取整個界面的觸摸事件
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.awen.camera.widget.CameraSurfaceView
android:id="@+id/cameraSurfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.awen.camera.widget.CameraFocusView
android:id="@+id/cameraFocusView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
......
3.定義對焦接口
i.定義接口
/**
* 聚焦的回調接口
*/
public interface IAutoFocus {
void autoFocus(float x,float y);
}
ii.對焦環View觸摸事件中觸發接口:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
int x = (int) event.getX();
int y = (int) event.getY();
lastValue = 0;
mPaint.setColor(Color.WHITE);
radius = (int) (mScreenWidth * 0.1);
centerPoint = null;
if(y>TOP_CONTROL_HEIGHT&&y<ScreenSizeUtil.getScreenHeight()-BETTOM_CONTROL_HEIGHT){//狀態欄和底部禁止點擊獲取焦點(顯示體驗不好)
centerPoint = new Point(x, y);
showAnimView();
//開始對焦
if (mIAutoFocus != null) {
mIAutoFocus.autoFocus(event.getX(),event.getY());
}
}
break;
}
return true;
}
4.在CameraSurfaceView實現對焦
i.計算對焦區域
private Rect caculateFocusPoint(int x, int y) {
Rect rect = new Rect(x - 100, y - 100, x + 100, y + 100);
int left = rect.left * 2000 / getWidth() - 1000;
int top = rect.top * 2000 / getHeight() - 1000;
int right = rect.right * 2000 / getWidth() - 1000;
int bottom = rect.bottom * 2000 / getHeight() - 1000;
// 如果超出了(-1000,1000)到(1000, 1000)的範圍,則會導致相機崩潰
left = left < -1000 ? -1000 : left;
top = top < -1000 ? -1000 : top;
right = right > 1000 ? 1000 : right;
bottom = bottom > 1000 ? 1000 : bottom;
return new Rect(left, top, right, bottom);
}
ii.設置參數進行對焦
private void camerFocus(Rect rect) {
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
if(cameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);//手動區域自動對焦
}
if (parameters.getMaxNumFocusAreas() > 0) {
List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
focusAreas.add(new Camera.Area(rect, 1000));
parameters.setFocusAreas(focusAreas);
}
mCamera.cancelAutoFocus(); // 先要取消掉進程中所有的聚焦功能
mCamera.setParameters(parameters);
mCamera.autoFocus(this);
}
四、拍照
爲了圖片方便預覽,需要對圖片進行處理,所以需要知道相機的拍照時的方向,故在拍照應先設置照片的方向參數
1.CameraOrientationDetector(Camera方向監聽器)
/**
* 方向變化監聽器,監聽傳感器方向的改變
* Created by AwenZeng on 2017/2/21.
*/
public class CameraOrientationDetector extends OrientationEventListener {
int mOrientation;
public CameraOrientationDetector(Context context, int rate) {
super(context, rate);
}
@Override
public void onOrientationChanged(int orientation) {
this.mOrientation = orientation;
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return;
}
//保證只返回四個方向,分別爲0°、90°、180°和270°中的一個
int newOrientation = ((orientation + 45) / 90 * 90) % 360;
if (newOrientation != mOrientation) {
mOrientation = newOrientation;
}
}
public int getOrientation() {
return mOrientation;
}
}
2.設置照片方向參數
/**
* 拍照
*
* @param callback
*/
public void takePicture(Camera.PictureCallback callback) {
if (mCamera != null) {
int orientation = mCameraOrientation.getOrientation();
Camera.Parameters cameraParameter = mCamera.getParameters();
if (orientation == 90) {
cameraParameter.setRotation(90);
cameraParameter.set("rotation", 90);
} else if (orientation == 180) {
cameraParameter.setRotation(180);
cameraParameter.set("rotation", 180);
} else if (orientation == 270) {
cameraParameter.setRotation(270);
cameraParameter.set("rotation", 270);
} else {
cameraParameter.setRotation(0);
cameraParameter.set("rotation", 0);
}
mCamera.setParameters(cameraParameter);
}
mCamera.takePicture(null, null, callback);
}
3.保存圖片
爲了方便預覽,對不同方向的圖片,需要做正向處理。
public String handlePhoto(byte[] data, int cameraId) {
String filePath = FileUtil.saveFile(data, "/DCIM");
if (!TextUtils.isEmpty(filePath)) {
int degree = BitmapUtil.getPhotoDegree(filePath);
Log.i(TAG, degree + "");
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Bitmap tBitmap = null;
try {
Log.i(TAG, "保存圖片大小:"+"width = " + bitmap.getWidth() + " ------ height = " + bitmap.getHeight());
if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
switch (degree) {
case 0:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 90);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 90:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 180);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 180:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 270);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 270:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 360);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
}
} else if (cameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) {
switch (degree) {
case 0:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 270);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 90:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 180);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 180:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 90);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
case 270:
tBitmap = BitmapUtil.rotateBitmap(bitmap, 360);
filePath = BitmapUtil.saveBitmap(tBitmap == null ? bitmap : tBitmap, filePath);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
// 重新拍照
return "";
} finally {
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
if (tBitmap != null) {
tBitmap.recycle();
tBitmap = null;
}
ScannerByReceiver(mContext, filePath);//圖庫掃描
}
return filePath;
}
return null;
}
五、切換攝像頭
/**
* 切換攝像頭
*/
public void changeCamera(int camera_id) {
mCamera.stopPreview();
mCamera.release();
try {
openCamera(camera_id);
mCamera.setPreviewDisplay(holder);
setCameraParams(DEFAULT_PHOTO_WIDTH, DEFAULT_PHOTO_HEIGHT);
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean openCamera(int camera_id) {
LogUtil.i(TAG, "openCamera id = " + camera_id);
try {
mCamera = Camera.open(camera_id); // 打開攝像頭
cameraId = camera_id;
} catch (Exception e) {
e.printStackTrace();
ToastUtil.getInstance().toast("請先開啓攝像頭權限");
LogUtil.i(TAG, "請先開啓攝像頭權限");
return false;
}
return true;
}
六、打開或關閉閃光燈
/**
* 設置閃光燈
*
* @param isOpen
*/
public void changeFlashMode(boolean isOpen, Camera mCamera, int cameraId) {
if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK) { // 後攝像頭纔有閃光燈
Camera.Parameters parameters = mCamera.getParameters();
PackageManager pm = mContext.getPackageManager();
FeatureInfo[] features = pm.getSystemAvailableFeatures();
for (FeatureInfo f : features) {
if (PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) { // 判斷設備是否支持閃光燈
if (isOpen) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // 開閃光燈
} else {
parameters
.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // 關閃光燈
}
}
}
mCamera.setParameters(parameters);
}
}
注意事項
- Android6.0以上權限收緊,所以在使用相機前,請用PermissionsModel做好權限判斷。具體Android6.0權限
- 部分智能手機,前置攝像頭無對焦模式,對焦參數設置應區分前置攝像頭
- Android5.0以後,官方推薦使用Camera2,本例子未使用新版本。