当我尝试将图像保存到图库时,应用程序不断崩溃

App keep crashing when I try to save image to gallery

我想拍张照片并将其保存到图库中。然后从图库中读取这张照片并将其转换为文本(使用 ocr)

但是当我尝试用这行代码保存它时我的应用程序一直崩溃

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

我调试我的应用程序,发现这一行是导致崩溃的原因。但是如果没有这条线,我就无法保存我的图像。我该怎么做?

package com.example.takepicture;

import ...

public class MainActivity extends AppCompatActivity {   
    private static final int CAMERA_REQUEST = 1888;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        Button btnCamera = (Button) findViewById(R.id.btnCamera);
        imageView = (ImageView) findViewById(R.id.ImageView); 

        btnCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String pictureName = getPictureName();

                File imageFile = new File(pictureDirectory,pictureName);
                Uri pictureUri = Uri.fromFile(imageFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
                //capturarFoto();


            }
        });

    }

    private String getPictureName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return "Img" + timeStamp + ".jpg";


    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST) {

            }
        }
    }
}

最快的解决方案是添加:

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

调用前某处: startActivityForResult(...)

但正确的(API >24)是:

  • 通过 FileProvider.getUriForFile(...)

  • 创建 URI
  • 正在创建提供程序(并将其添加到清单文件)

您可以在那里找到更多信息: