在我的应用程序中获取相机拍摄的图像时遇到问题。

当我尝试获取该文件时,它不存在。我不明白问题出在哪里:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    this.imageView = (ImageView)this.findViewById(R.id.imageView1);
    Button photoButton = (Button) this.findViewById(R.id.button1);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            Uri uri = Uri.parse("/sdcard/Images/test_image.jpg");
            Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

        File image=new File("/sdcard/Images/","test_image.jpg");
        if (image.exists()){
             Bitmap bm = BitmapFactory.decodeFile("/sdcard/Images/test_image.jpg");
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
             byte[] b = baos.toByteArray();
        }
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }
}

当它到达 image.exists() 时,它说 false。我已经在 list 上写了 sd 写权限。

最佳答案

Uri.parse 创建一个解析给定的编码 URI 字符串而不是文件路径的 uri,sdcard 上不存在。所以无论是用户 "file://"+ filename_with_path 还是使用 Uri.fromFile 从文件路径创建 URI。还使用 Environment.getExternalStorageDirectory() 而不是 sdcard 的静态路径:

File dir = Environment.getExternalStorageDirectory();
file = new File(dir, "test_image.jpg");
Uri uri = Uri.fromFile(file);

Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(photoIntent, CAMERA_REQUEST);

第二个 主要问题是您正在传递 cameraIntent Intent ,其中您没有将 MediaStore.EXTRA_OUTPUT 添加到 startActivityForResult 。所以将 photoIntent 传递给 startActivityForResult 因为您在 photoIntent Intent 实例中添加 MediaStore.EXTRA_OUTPUT 键而不是 cameraIntent

关于android - 文件不存在由相机拍摄的android图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21984570/

10-11 22:15
查看更多