Android相机

作者:某人_Valar
如需转载请保留原文链接;

在Android的开发过程中,目前使用相机大概分为两种方式,一种是直接拉起系统的相机进行拍照,另一种就是自定义一个相机界面。

关于自定义相机的使用:

在自定义相机中我们就可以自定义拍照的界面,设置拍照的参数等。


一个自定义的相机界面

主要是一个自定义的Activity,

  1. 使用CameraPreview 进行预览,
  2. 然后调用Camera的takePicture方法拍照,
  3. 之后再对应的回调中保存或者展示即可。
public class CameraActivity extends Activity {
    protected static final String TAG = "raycamera";
    private Camera mCamera;
    private int cameraPosition = 0;//0代表后置摄像头,1代表前置摄像头
    private SurfaceHolder mHolder;
    static CameraActivity mInstance = null;
    private File compressFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);

        CameraPreview mPreview = new CameraPreview(this);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
        mInstance = this;
    }

    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(0);
        } catch (Exception e) {
            // Camera is notavailable (in use or does not exist)
        }
        return c;
    }

    @OnClick(R.id.capture_iv)
    void takePic() {
        mCamera.takePicture(null, null, mPicture);
        tip("拍照中,请保持手机稳定");
    }

    //点击屏幕进行对焦
    @OnClick(R.id.camera_preview)
    void autoFocus() {
        try {
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.changeCamera_iv)
    void changeCamera() {
        //切换前后摄像头
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        int cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
            if (cameraPosition == 0) {
                //现在是后置,变更为前置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    if (mCamera != null) {
                        mCamera.stopPreview();//停掉原来摄像头的预览
                        mCamera.release();//释放资源
                        mCamera = null;//取消原来摄像头
                    }
                    Log.d(TAG, "open front ,i = " + i);
                    mCamera = Camera.open(i);//打开当前选中的摄像头
                    try {
                        mCamera.setPreviewDisplay(mHolder);//通过surfaceview显示取景画面
                        mCamera.setDisplayOrientation(90);
                        setCameraParms(mCamera);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();//开始预览
                    cameraPosition = 1;
                    break;
                }
            } else {
                //现在是前置, 变更为后置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    if (mCamera != null) {
                        mCamera.stopPreview();//停掉原来摄像头的预览
                        mCamera.release();//释放资源
                        mCamera = null;//取消原来摄像头
                    }
                    Log.d(TAG, "open back ,i = " + i);
                    mCamera = Camera.open(i);//打开当前选中的摄像头
                    try {
                        mCamera.setPreviewDisplay(mHolder);//通过surfaceview显示取景画面
                        mCamera.setDisplayOrientation(90);
                        setCameraParms(mCamera);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();//开始预览
                    cameraPosition = 0;
                    break;
                }
            }
        }
    }

    public class CameraPreview extends SurfaceView implements
            SurfaceHolder.Callback {
        // private Camera mCamera;
        public CameraPreview(Context context) {
            super(context);
            //mCamera = camera;
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecatedsetting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        public void surfaceCreated(SurfaceHolder holder) {
            Log.d(TAG, "surfaceCreated: ");
            cameraPosition = 0;//创建时设置默认后置摄像头
            mCamera = getCameraInstance();

            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.setDisplayOrientation(90);
                mCamera.startPreview();
            } catch (IOException e) {
                Log.d(TAG, "Errorsetting camera preview: " + e.getMessage());
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.d(TAG, "surfaceDestroyed: ");
            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w,
                                   int h) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.
            Log.d(TAG, "surfaceChanged ");
            if (mHolder.getSurface() == null) {
                return;
            }

            try {
                mCamera.stopPreview();
            } catch (Exception e) {
                // ignore: triedto stop a non-existent preview
            }

            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.setDisplayOrientation(90);
                mCamera.startPreview();
                setCameraParms(mCamera);
            } catch (Exception e) {
                Log.d(TAG, "Errorstarting camera preview: " + e.getMessage());
            }
        }
    }

    private void setCameraParms(Camera camera) {
        Camera.Parameters params = camera.getParameters();
        //设置相机保存图片的尺寸大小
        List supportSizes = params.getSupportedPictureSizes();
        Camera.Size bestSize = supportSizes.get(0);
        for (int i = 1; i < supportSizes.size(); i++) {
            if ((supportSizes.get(i).width * supportSizes.get(i).height) > (bestSize.width * bestSize.height)) {
                bestSize = supportSizes.get(i);
            }
        }
        params.setPictureSize(bestSize.width, bestSize.height);
        camera.setParameters(params);
    }

    Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {

        }
    };

    //拍照结束后的回调
    private PictureCallback mPicture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            camera.stopPreview();
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/songshucang");
            boolean isFileCreated = file.exists();
            if (!isFileCreated) {
                isFileCreated = file.mkdir();
            }
            if (isFileCreated) {
                Bitmap bm = BitmapFactory.decodeByteArray(data, 0, (data != null) ? data.length : 0);
                final Matrix matrix = new Matrix();
                if (cameraPosition == 0) {
                    matrix.setRotate(90);
                } else {
                    matrix.setRotate(270);
                }
                final Bitmap bitmap =
                        Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA)
                        .format(new Date());
                String photoPath = file + "/ssc/IMG_" + timeStamp;
                try {
                    saveImageToSD(CameraActivity.this,
                            photoPath, bitmap, 90);
                    //拍照完成后用广播通知系统相册更新,否则可能在相册中看不见刚保存的图片
                    File fileTemp = new File(photoPath);
                    Uri uri =  Uri.fromFile(fileTemp);  
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(uri);
                    CameraActivity.this.sendBroadcast(intent);
                } catch (FileNotFoundException e) {
                    Log.i("cameratest", "File notfound: " + e.getMessage());
                } catch (IOException e) {
                    Log.i("cameratest", "Erroraccessing file: " + e.getMessage());
                }
            }
        }
    };

    //保存图片
    public void saveImageToSD(String filePath,
                              Bitmap bitmap, int quality) throws IOException {
        if (bitmap != null) {
            File file = new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }


}

布局文件如下:




        
        

        

        

            

            

            


有时候我们会发现拍照保存的图片在相册中查看不到,这是因为没有通知系统相册更新。

       //拍照完成后用广播通知系统相册更新
       File fileTemp = new File(photoPath);
       Uri uri =  Uri.fromFile(fileTemp);  
       Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
       intent.setData(uri);
       CameraActivity.this.sendBroadcast(intent);

你可能感兴趣的:(Android相机)