Android Camera2 拍照(二)——使用TextureView

來源:互聯網
上載者:User

標籤:format   tco   展示   surface   err   地址   catch   over   default   

原文:Android Camera2 拍照(二)——使用TextureView

上一篇博文簡單介紹了使用Camera2 API拍攝照片,並使用SurfaceView作為預覽介面。實際上,相對於SurfaceView, TextureView更適合用於視頻和拍攝照片。SurfaceView也有它的使用場合,這將在另外一篇中闡述。本文將使用TextureView作為預覽介面,再次向大家展示Camera2 API的簡單應用。

1,定義TextureView作為預覽介面

在布局檔案中加入TextureView控制項,然後實現其監聽事件

textureView = (TextureView) findViewById(R.id.textureView);
然後我們可以在OnResume()方法中設定監聽SurefaceTexture的事件

textureView.setSurfaceTextureListener(textureListener);

當SurefaceTexture準備好後會回調SurfaceTextureListener 的onSurfaceTextureAvailable()方法

private TextureView.SurfaceTextureListener mTextureListener = new TextureView.SurfaceTextureListener() {        @Override        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {            //當SurefaceTexture可用的時候,設定相機參數並開啟相機            setupCamera(width, height);            openCamera();        }        @Override        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {        }        @Override        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {            return false;        }        @Override        public void onSurfaceTextureUpdated(SurfaceTexture surface) {        }    };
2,設定相機參數

private void setupCamera(int width, int height) {        //擷取網路攝影機的管理者CameraManager        CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);        try {            //遍曆所有網路攝影機            for (String cameraId : manager.getCameraIdList()) {                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);                //此處預設開啟後置網路攝影機                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT)                    continue;                //擷取StreamConfigurationMap,它是管理網路攝影機支援的所有輸出格式和尺寸                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);                assert map != null;                //根據TextureView的尺寸設定預覽尺寸                mPreviewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height);                //擷取相機支援的最大拍照尺寸                mCaptureSize = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new Comparator<Size>() {                    @Override                    public int compare(Size lhs, Size rhs) {                        return Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getHeight() * rhs.getWidth());                    }                });                //此ImageReader用於拍照所需                setupImageReader();                mCameraId = cameraId;                break;            }        } catch (CameraAccessException e) {            e.printStackTrace();        }    }

//選擇sizeMap中大於並且最接近width和height的size    private Size getOptimalSize(Size[] sizeMap, int width, int height) {        List<Size> sizeList = new ArrayList<>();        for (Size option : sizeMap) {            if (width > height) {                if (option.getWidth() > width && option.getHeight() > height) {                    sizeList.add(option);                }            } else {                if (option.getWidth() > height && option.getHeight() > width) {                    sizeList.add(option);                }            }        }        if (sizeList.size() > 0) {            return Collections.min(sizeList, new Comparator<Size>() {                @Override                public int compare(Size lhs, Size rhs) {                    return Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getWidth() * rhs.getHeight());                }            });        }        return sizeMap[0];    }

private void setupImageReader() {        //2代表ImageReader中最多可以擷取兩幀映像流        mImageReader = ImageReader.newInstance(mCaptureSize.getWidth(), mCaptureSize.getHeight(),                ImageFormat.JPEG, 1);        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {            @Override            public void onImageAvailable(ImageReader reader) {                final Image image = reader.acquireNextImage();                mCameraHandler.post(new imageSaver(image));                getActivity().runOnUiThread(new Runnable() {                    @Override                    public void run() {                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();                        byte[] bytes = new byte[buffer.remaining()];                        buffer.get(bytes);//由緩衝區存入位元組數組                        final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);                        if (bitmap != null) {                            ivShow.setImageBitmap(bitmap);                        }                    }                });            }        }, mCameraHandler);    }
public static class imageSaver implements Runnable {        private Image mImage;        public imageSaver(Image image) {            mImage = image;        }        @Override        public void run() {            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();            byte[] data = new byte[buffer.capacity()];            buffer.get(data);            String path = Environment.getExternalStorageDirectory() + "/DCIM/361camera/";            File mImageFile = new File(path);            if (!mImageFile.exists()) {                boolean ret = mImageFile.mkdirs();                assert (ret);            }            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());            String fileName = path + "IMG_" + timeStamp + ".jpg";            FileOutputStream fos = null;            try {                fos = new FileOutputStream(fileName);                fos.write(data, 0, data.length);            } catch (IOException e) {                e.printStackTrace();            } finally {                if (fos != null) {                    try {                        fos.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                mImage.close();            }        }    }
3,開啟相機

private void openCamera() {        mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);        try {            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {                //申請WRITE_EXTERNAL_STORAGE許可權                requestPermissions(new String[]{Manifest.permission.CAMERA},                        REQUEST_CAMERA_CODE);                //return;            } else {                mCameraManager.openCamera(mCameraId, mStateCallback, mCameraHandler);            }        } catch (CameraAccessException e) {            e.printStackTrace();        }    }

實現StateCallback 介面,當相機開啟後會回調onOpened方法,在這個方法裡面開啟預覽

private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {        @Override        public void onOpened(CameraDevice camera) {            mCameraDevice = camera;            startPreview();        }        @Override        public void onDisconnected(CameraDevice camera) {            camera.close();            mCameraDevice = null;        }        @Override        public void onError(CameraDevice camera, int error) {            camera.close();            mCameraDevice = null;        }    };

4,開啟相機預覽

private void startPreview() {        SurfaceTexture mSurfaceTexture = mTextureView.getSurfaceTexture();        mSurfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());        Surface previewSurface = new Surface(mSurfaceTexture);        try {            mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);            mCaptureRequestBuilder.addTarget(previewSurface);            mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() {                @Override                public void onConfigured(CameraCaptureSession session) {                    try {                        mCaptureRequest = mCaptureRequestBuilder.build();                        mCameraCaptureSession = session;                        mCameraCaptureSession.setRepeatingRequest(mCaptureRequest, null, mCameraHandler);                    } catch (CameraAccessException e) {                        e.printStackTrace();                    }                }                @Override                public void onConfigureFailed(CameraCaptureSession session) {                }            }, mCameraHandler);        } catch (CameraAccessException e) {            e.printStackTrace();        }    }

5,實現PreviewCallback

首先建立一個ImageReader,並監聽它的事件(見上面的代碼setupImageReader())。然後開啟預覽之前,設定ImageReader為輸出Surface(見上面setupCamera()的代碼)。

6,拍照


public void takePicture() {        lockFocus();    }    private void lockFocus() {        try {            mCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);            mCameraCaptureSession.capture(mCaptureRequestBuilder.build(), mCaptureCallback, mCameraHandler);        } catch (CameraAccessException e) {            e.printStackTrace();        }    }

原始碼地址:https://github.com/gengqifu/361Camera。歡迎順手star一下~~~


Android Camera2 拍照(二)——使用TextureView

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.