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

时间:2019-03-08 14:43:48

标签: java android android-intent uri android-camera-intent

我想拍摄一张照片并将其保存到画廊。然后从图库中读取这张照片,并将其转换为文本(使用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) {

            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

最快的解决方案是添加:

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

致电之前的某个地方: startActivityForResult(...)

但是正确的(对于API> 24)是:

  • 通过FileProvider.getUriForFile(...)

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

您可以在此处找到更多信息:https://stackoverflow.com/a/50265329/5529263