我的相机 2 API 无法拍照

My camera2 API getting stuck on taking a picture

我正在使用 Camera 2 API 制作相机应用程序 API,我显示预览的代码运行良好,它还可以从预览中单击图片并将它们存储在目录中。 我的问题是: 拍照和存储时卡住,存储照片后相机正常工作。

这是我获取预览图像并存储它的代码:

onTakePhotoButtonClicked():

public void onTakePhotoButtonClicked() {
    FileOutputStream outputPhoto = null;
    try {
        outputPhoto = new FileOutputStream(createImgFile());
        preview.getBitmap()
                .compress(Bitmap.CompressFormat.PNG, 100, outputPhoto);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (outputPhoto != null) {
                outputPhoto.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

createImgFile():

private File createImgFile() throws IOException{

    String TimeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String prepend = "IMG_"+TimeStamp+"_";
    File Imgfile = File.createTempFile(prepend,".jpg",mPictureFolder);
    mPictureFileName = Imgfile.getAbsolutePath();
    Toast.makeText(getApplicationContext(),mPictureFileName.toString(),Toast.LENGTH_SHORT).show();
    return Imgfile;
}

onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_mycamera_experiment);
    preview = (TextureView) findViewById(R.id.preview);
    click = (ImageButton) findViewById(R.id.click);
    createImgFolder();

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT );

    click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onTakePhotoButtonClicked();

        }
    });
}

有没有办法让拍照和返回相机的速度更快? 有什么更正,更好的方法吗?

因为您正在 UI 线程中保存位图。 您应该在工作线程中保存位图。

还有,如果要拍照,最好用ImageReaderApi。 我认为保存 TextureView 的位图不是一个好主意。