Android 照相机 camera 操作封装

news/2024/11/29 4:48:03/

项目中经常用到Android自带的camera拍照功能。于是做了个封装,CameraUtil.java类。

再次用到就简单啦,可以最大限度的复用提高效率。

我最喜欢对常用的功能模块进行封装,因为优秀的代码思想就是要追求最大化的复用和高效率。推荐《重构》和《程序员修炼之道》书籍。不要觉得这类书籍有些理论比较空洞,不如看某某实战之类的书籍。其实这类书籍影响的是人的思想,思想改变远比你多学几行代码重要。

好的封装,能使你做事事半功倍,像搭积木一样快速的实现应用。为啥有的大牛做东西很快?原因无他,肯定是沉淀积累了很多可以复用的轮子。

封装后的CameraUtil类使用很简单。

先来张效果图:

封装后的CameraUtil类使用有多简单?

 if (cameraUtil == null){int rotation = getWindowManager().getDefaultDisplay().getRotation();cameraUtil = new CameraUtil(surfaceView, 0,rotation, takeButton, onPictureListener);cameraUtil.start();}

只需传进去五个参数即可。第一个就是预览的界面surfaceView,第二个参数相机ID,默认为0.第三个参数图像旋转的角度。第四个参数拍照的按钮。onPictureListener为拍完照片的回调处理。

/** 拍照信息回调*/OnPictureListener onPictureListener = new OnPictureListener() {@Overridepublic void getPicture(Drawable drawable) {//getCameraPicture(drawable);final Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();Log.d(TAG,"take picture bitmap size kb:"+bitmap.getByteCount()/1024);DataConstant.photo = Utils.bitmapToString(bitmap);File tempFile = new File("/sdcard/temp0.png");try {FileOutputStream fos = new FileOutputStream(tempFile);bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);//写入,这里会卡顿,因为图片较大fos.flush();//记得要关闭写入流fos.close();}catch (Exception ex){ex.printStackTrace();}
}

封装如下:

package com.newcapec.fkrobot.util;import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;import com.newcapec.fkrobot.app.App;
import com.newcapec.fkrobot.interf.OnPictureListener;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;/*** @author : yangyognzhen* @date :2020/7/11 14:19* @description:**/
public class CameraUtil {private String TAG = this.getClass().getSimpleName();//相机和相机预览mSurfaceViewprivate Camera mCamera;private SurfaceView mSurfaceView;private SurfaceHolder mHolder;//摄像头支持的分辨率private Camera.Size mPreviewSize;private List mSupportedPreviewSizes;//private Activity activity;private View button;private int mCameraId;private int additionalRotation;private int displayOrientation = 0;private int rotation;private OnPictureListener onFinishListener;private static CameraUtil _instance;public static CameraUtil getInstance(SurfaceView surfaceView, int cameraId, int rotation, View button, OnPictureListener onFinishListener) {if (_instance == null)_instance = new CameraUtil(surfaceView,cameraId,rotation,button,onFinishListener);return _instance;}public CameraUtil(SurfaceView surfaceView, int cameraId, int rotation, View button, OnPictureListener onFinishListener){this.mSurfaceView = surfaceView;this.button = button;this.onFinishListener = onFinishListener;mCameraId = cameraId;this.rotation = rotation;//初始化相机预览及回调initData(cameraId);}private void initData(int id) {//增加surfaceview回调mHolder= mSurfaceView.getHolder();mHolder.addCallback(callback);//mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);mPreviewSize=getPreviewSize(id);// mCamera.setDisplayOrientation(270);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Camera.Parameters parameters = mCamera.getParameters();parameters.setJpegQuality(100);  //生成图像的质量mCamera.setParameters(parameters);parameters.setPictureFormat(ImageFormat.JPEG);parameters.setPictureSize(640, 480); //生成图像的风辨率mCamera.setParameters(parameters);
//                int ro = displayOrientation+90;
//                if(ro >= 360){
//                    ro = 0;
//                }parameters.setRotation(displayOrientation);  //生成的图像旋转90度mCamera.setParameters(parameters);//拍照的提示音shootSound();mCamera.takePicture(null,null, new Camera.PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {// 主要就是将图片转化成drawable,设置为固定区域的背景(展示图片),当然也可以直接在布局文件里放一个surfaceView供使用。ByteArrayInputStream bais = new ByteArrayInputStream(data);Drawable d = BitmapDrawable.createFromStream(bais, Environment.getExternalStorageDirectory().getAbsolutePath()+ "/img.jpeg");Bitmap bitmap = ((BitmapDrawable) d).getBitmap();Log.d(TAG,"fk picture bitmap size kb:"+bitmap.getByteCount()/1024);File tempFile = new File("/sdcard/temp.png");try {FileOutputStream fos = new FileOutputStream(tempFile);fos.write(data);fos.close();}catch (Exception ex){ex.printStackTrace();}if(onFinishListener != null){onFinishListener.getPicture(d);}mCamera.startPreview();try {} catch (Exception e) {e.printStackTrace();}}});}});}private Camera.Size getPreviewSize(int id){mCamera = Camera.open(id);// mCamera.setDisplayOrientation(270);displayOrientation = getCameraOri(rotation);Log.e(TAG,"camera displayOrientation:"+displayOrientation);mCamera.setDisplayOrientation(displayOrientation);setCamera(mCamera);if(mCamera!=null){Camera.Parameters parameters = mCamera.getParameters();//获取摄像头支持的分辨率List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();//遍历输出摄像头支持的所有分辨率for(Camera.Size s: sizes){Log.e(TAG,"size====="+s.width+"X"+s.height);}Camera.Size optimalSize = Utils.getOptimalPreviewSize(sizes, sizes.get(0).height, sizes.get(0).width);return optimalSize;}return null;}private void setCamera(Camera camera) {mCamera = camera;if (mCamera != null) {mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();}try {camera.setPreviewDisplay(mHolder);} catch (IOException exception) {Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);}Camera.Parameters parameters = camera.getParameters();// 设置相片格式parameters.setJpegQuality(100);  //生成图像的质量mCamera.setParameters(parameters);parameters.setPictureFormat(ImageFormat.JPEG);//parameters.setPreviewFormat(ImageFormat.YV12);//parameters.setPictureFormat(ImageFormat.FLEX_RGB_888);// 设置预览大小//parameters.setPreviewSize(640, 480);parameters.setPictureSize(640, 480); //生成图像的风辨率mCamera.setParameters(parameters);//List sizes = parameters.getSupportedPreviewSizes();//Camera.Size optimalSize = Utils.getOptimalPreviewSize(sizes, 1920, 1080);//parameters.setPreviewSize(optimalSize.width, optimalSize.height);//设置摄像头翻转角度//parameters.setRotation(90);//设置镜像效果,支持的值为flip-mode-values=off,flip-v,flip-h,flip-vh;//flip-mode-values规定了翻转(镜像)模式的取值只能为off(关闭),flip-v(竖直翻转),flip-h(水平翻转),flip-vh(竖直+水平翻转)//parameters.set("preview-flip", "flip-vh");camera.setParameters(parameters);}SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {@Overridepublic void surfaceCreated(SurfaceHolder holder) {try {if (mCamera != null) {//建立预览界面mCamera.setPreviewDisplay(holder);//mCamera.setDisplayOrientation(270);}} catch (IOException exception) {Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);}}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {if(mCamera != null){Camera.Parameters parameters = mCamera.getParameters();parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 1连续对焦setDispaly(parameters, mCamera);//开始预览mCamera.startPreview();}}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {if (mCamera != null) {mCamera.stopPreview();}}};/** 控制图像的正确显示方向*/private void setDispaly(Camera.Parameters parameters, Camera camera) {if (Integer.parseInt(Build.VERSION.SDK) >= 8) {// setDisplayOrientation(camera, 0);} else {// parameters.setRotation(90);}}private int getCameraOri(int rotation) {int degrees = rotation * 90;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;default:break;}additionalRotation /= 90;additionalRotation *= 90;degrees += additionalRotation;int result;Camera.CameraInfo info = new Camera.CameraInfo();Camera.getCameraInfo(mCameraId, info);if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {result = (info.orientation + degrees) % 360;result = (360 - result) % 360;} else {result = (info.orientation - degrees + 360) % 360;}return result;}/** 实现的图像的正确显示*/private void setDisplayOrientation(Camera camera, int i) {Method downPolymorphic;try {downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class});if (downPolymorphic != null) {downPolymorphic.invoke(camera, new Object[]{i});}} catch (Exception e) {Log.e("Came_e", "图像出错");}}/***   播放系统拍照声音*/public void shootSound() {MediaPlayer shootMP;AudioManager meng = (AudioManager) App.getContext().getSystemService(Context.AUDIO_SERVICE);int volume = meng.getStreamVolume( AudioManager.STREAM_NOTIFICATION);if (volume != 0) {shootMP = MediaPlayer.create(App.getContext(), Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));shootMP.start();}}/*** 开启拍照*/public void start() {synchronized (this) {if (mCamera != null) {return;}//initData(0);mCamera.startPreview();}}/*** 停掉摄像头拍照*/public void stop() {synchronized (this) {if (mCamera == null) {return;}mCamera.stopPreview();mCamera.release();mCamera = null;Log.e(TAG,"释放摄像头");}}}


http://www.ppmy.cn/news/249734.html

相关文章

Android实战开发:自定义照相机

参考资料&#xff1a; SurfaceView&#xff1a;http://www.cnblogs.com/xuling/archive/2011/06/06/android.html android.hardware.Camera2&#xff1a;http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0428/2811.html Camera默认捕获画面横向&#xff1a; ht…

照相机定标

作者 群号 C语言交流中心 240137450 微信 15013593099 照相机定标 [ 编辑] ProjectPoints2 投影三维点到图像平面 void cvProjectPoints2( const CvMat* object_points, const CvMat* rotation_vector,const CvMat* translation_vector, const CvMat* intrinsic_matrix,cons…

Android Top Camera Libraries 照相机API 库推荐

lsmore2018-11-30移动开发1评论 CameraView CameraView 旨在帮助Android开发者更便利地集成照相功能 Features 特性 Camera preview by placing it in a layout XML (and calling the start method)Configuration by attributesAspect ratio (app:aspectRatio)Auto-focus (…

Android如何控制照相机

本文译自&#xff1a;http://developer.android.com/training/camera/cameradirect.html 本文中&#xff0c;我们讨论如何使用框架API来直接的控制照相机硬件。 直接控制设备等的照相机&#xff0c;比从既存的照相机应用程序中获取图片或视频需要更多的编码。但是&#xff0c;如…

补番推荐

目录 first弹丸论破 second 学园默示录 third罪恶王冠 FIRST 弹丸论破 http://v.pptv.com/show/Dym1MpoAcK4Rj1M.html 本作在背景设定方面&#xff0c;游戏中当玩家们找出犯人的时候&#xff0c;犯人将会因此而被处置杀害。不过如果玩家们不能找出真正的犯人&#xff0c…

自定义照相机官方指南

文章翻译自谷歌API指南&#xff0c;摘取了自定义相机部分。文中连接直接调到官方文档&#xff0c;请自备梯子。也可以下载一个离线API文档&#xff0c;直接搜索相关API查看API使用说明。 原文链接&#xff1a;Camera 一、相关权限声明 以下权限及特性根据情况添加。<uses…

常见的样本统计量及其数字特征

常见的样本统计量及其数字特征 下图来自《统计学图鉴》 样本统计量有什么作用&#xff1f; 因为总体特征包含有总体均值、总体方差等特征&#xff0c;我们在用样本推断总体时&#xff0c;其实就是用样本特征去估计总体特征&#xff0c;例如&#xff1a;样本均值这个统计量的期…

无线洗地机哪个牌子好?高品质洗地机推荐

随着科技的不断发展&#xff0c;大家在地面清洁工具方面有了更多的选择&#xff0c;从一开始的扫地机器人到吸尘器&#xff0c;再到现在的智能洗地机&#xff0c;可谓是各有各的优势&#xff0c;但是要论地面清洁能力的话&#xff0c;洗地机是当值之无愧的&#xff0c;不仅干湿…