這篇文章給大家介紹怎么在Android中通過自定義Camera實現拍照功能,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
站在用戶的角度思考問題,與客戶深入溝通,找到且末網站設計與且末網站推廣的解決方案,憑借多年的經驗,讓設計與互聯網技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網站設計制作、成都網站建設、企業(yè)官網、英文網站、手機端網站、網站推廣、域名申請、虛擬空間、企業(yè)郵箱。業(yè)務覆蓋且末地區(qū)。
Camera類在5.0以后不推薦使用了,取而代之的是android.hardware.camera2包下的類,本文使用Camera。
我們首先自定義一個View去繼承SurfaceView:
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback { private SurfaceHolder mHolder; private Camera mCamera; private static final int ORIENTATION = 90; private int mScreenWidth; private int mScreenHeight; private boolean isOpen; public CameraSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); getScreenMatrix(context); mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } private void getScreenMatrix(Context context) { WindowManager WM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); WM.getDefaultDisplay().getMetrics(outMetrics); mScreenWidth = outMetrics.widthPixels; mScreenHeight = outMetrics.heightPixels; } public void takePicture(Camera.ShutterCallback mShutterCallback, Camera.PictureCallback rawPictureCallback, Camera.PictureCallback jpegPictureCallback) { if (mCamera != null) mCamera.takePicture(mShutterCallback, rawPictureCallback, jpegPictureCallback); } public void startPreview() { mCamera.startPreview(); } @Override public void surfaceCreated(SurfaceHolder holder) { if (!checkCameraHardware(getContext())) return; if (mCamera == null) { isOpen = safeCameraOpen(Camera.CameraInfo.CAMERA_FACING_BACK); } if (!isOpen) { return; } mCamera.setDisplayOrientation(ORIENTATION); try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (mCamera != null) { setCameraParams(mScreenWidth, mScreenHeight); mCamera.startPreview(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { releaseCameraAndPreview(); } private boolean safeCameraOpen(int id) { boolean qOpened = false; try { releaseCameraAndPreview(); mCamera = Camera.open(id); qOpened = (mCamera != null); } catch (Exception e) { e.printStackTrace(); } return qOpened; } private void releaseCameraAndPreview() { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) { return true; } else { return false; } } @Override public void onAutoFocus(boolean success, Camera camera) { } private void setCameraParams(int width, int height) { Camera.Parameters parameters = mCamera.getParameters(); // 獲取攝像頭支持的PictureSize列表 List<Camera.Size> pictureSizeList = parameters.getSupportedPictureSizes(); /**從列表中選取合適的分辨率*/ Camera.Size picSize = getProperSize(pictureSizeList, ((float) height / width)); if (null == picSize) { picSize = parameters.getPictureSize(); } // 根據選出的PictureSize重新設置SurfaceView大小 float w = picSize.width; float h = picSize.height; parameters.setPictureSize(picSize.width, picSize.height); this.setLayoutParams(new RelativeLayout.LayoutParams((int) (height * (h / w)), height)); // 獲取攝像頭支持的PreviewSize列表 List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes(); Camera.Size preSize = getProperSize(previewSizeList, ((float) height) / width); if (null != preSize) { parameters.setPreviewSize(preSize.width, preSize.height); } parameters.setJpegQuality(100); // 設置照片質量 if (parameters.getSupportedFocusModes().contains(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 連續(xù)對焦模式 } mCamera.setDisplayOrientation(90);// 設置PreviewDisplay的方向,效果就是將捕獲的畫面旋轉多少度顯示 mCamera.setParameters(parameters); } /** * 選取合適的分辨率 */ private Camera.Size getProperSize(List<Camera.Size> pictureSizeList, float screenRatio) { Camera.Size result = null; for (Camera.Size size : pictureSizeList) { float currentRatio = ((float) size.width) / size.height; if (currentRatio - screenRatio == 0) { result = size; break; } } if (null == result) { for (Camera.Size size : pictureSizeList) { float curRatio = ((float) size.width) / size.height; if (curRatio == 4f / 3) {// 默認w:h = 4:3 result = size; break; } } } return result; } }
代碼沒什么難度,在View創(chuàng)建的時候完成Camera的初始化,然后對Camera進行參數的設置(圖片尺寸,質量之類的),最后別忘了在View銷毀的時候對資源進行釋放。
控件定義完了之后我們就要去使用它,在布局文件中添加就OK:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" > <com.padoon.cameratest.CameraSurfaceView android:id="@+id/sv_camera" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="4"/> <ImageView android:id="@+id/img_take_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_gravity="bottom" android:layout_marginBottom="10dp" android:layout_marginRight="10dp" android:src="@mipmap/icon_camera"/> </RelativeLayout>
然后在Activity中去完成拍照功能:
public class CameraActivity extends AppCompatActivity { private boolean isClick = true; private static final String PATH_IMAGES = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "easy_check"; private CameraSurfaceView mCameraSurfaceView; //拍照快門的回調 private Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() { @Override public void onShutter() { } }; //拍照完成之后返回原始數據的回調 private Camera.PictureCallback rawPictureCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { } }; //拍照完成之后返回壓縮數據的回調 private Camera.PictureCallback jpegPictureCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { mCameraSurfaceView.startPreview(); saveFile(data); Toast.makeText(CameraActivity.this, "拍照成功", Toast.LENGTH_SHORT).show(); isClick = true; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView img_take_photo = (ImageView) findViewById(R.id.img_take_photo); mCameraSurfaceView = (CameraSurfaceView) findViewById(R.id.sv_camera); img_take_photo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { takePhoto(); } }); } public void takePhoto() { if (isClick) { isClick = false; mCameraSurfaceView.takePicture(mShutterCallback, rawPictureCallback, jpegPictureCallback); } } //保存圖片到硬盤 public void saveFile(byte[] data) { String fileName = UUID.randomUUID().toString() + ".jpg"; FileOutputStream outputStream = null; try { File file = new File(PATH_IMAGES); if (!file.exists()) { file.mkdirs(); } outputStream = new FileOutputStream(PATH_IMAGES + File.separator + fileName); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); bufferedOutputStream.write(data, 0, data.length); } catch (Exception e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
最后記得添加拍照跟磁盤操作權限:
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Android是一種基于Linux內核的自由及開放源代碼的操作系統(tǒng),主要使用于移動設備,如智能手機和平板電腦,由美國Google公司和開放手機聯盟領導及開發(fā)。
關于怎么在Android中通過自定義Camera實現拍照功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
分享標題:怎么在Android中通過自定義Camera實現拍照功能
新聞來源:http://jinyejixie.com/article16/posddg.html
成都網站建設公司_創(chuàng)新互聯,為您提供定制網站、外貿網站建設、小程序開發(fā)、關鍵詞優(yōu)化、網站排名、微信小程序
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯