至于如何在项目中如何添加OpenCv的SDK在此不再赘述:我引入的OpenCv-SDK版本为OpenCV-3.1.0-android-sdk
在Activity中实现CameraBridgeViewBase.CvCameraViewListener2接口并重写其方法,在
Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)方法中可以使用OpenCv的保存图片的方法,如下:
Imgcodecs.imwrite("/storage/emulated/0/" + "OpenCvimwrite.jpg", inputFrame.rgba());
方法参数为:1.图片名称(包括路径)2.Mat类型的数据
注:此方法保存的图片分辨率和预览分辨率相同(即Camera的PreviewSize属性)
另外此图片可能比较模糊,通过查看 JavaCameraView类中的Boolean initializeCamera(int width,int height)方法发现有以下两行代码:
- int size = mFrameWidth * mFrameHeight;
- size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
- size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat());
下面切入主题,添加保存照片的方法:
在JavaCameraView类中添加方法:
- public void tackPhoto(final String name) {
- if (mCamera != null) {
- mCamera.takePicture(null, null, new Camera.PictureCallback() {
- @Override
- public void onPictureTaken(byte[] data, Camera camera) {
- Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
- saveMyBitmap(bmp, name);
- }
- });
- }
- public void saveMyBitmap(Bitmap mBitmap, String photoName) {
- if (isMediaMounted()) {
- String SDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
- createFileDir(SDCardPath + File.separator + "OpenCv");
- String FilePath = SDCardPath + File.separator + "OpenCv" + File.separator + photoName + ".jpg";
- File file = new File(FilePath);
- // "/storage/emulated/0/OpenCv" + "OpenCv.jpg",
- BufferedOutputStream bos = null;
- try {
- FileOutputStream fos = new FileOutputStream(file);
- bos = new BufferedOutputStream(fos);
- mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
- bos.flush();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (mBitmap != null) {
- mBitmap.recycle();
- }
- bos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- } else {
- Log.e(TAG, "saveMyBitmap: 没有挂载内存卡,无法保存图片");
- }
- }
- /**
- * SD卡是否挂载
- *
- * @return
- */
- public static boolean isMediaMounted() {
- String status = Environment.getExternalStorageState();
- if (status.equals(Environment.MEDIA_MOUNTED)) {
- return true;
- } else {
- return false;
- }
- }
这样在Activity中就可以调用 JavaCameraView的 tackPhoto()方法拍照了。