当使用缓存URI作为MediaStore时,照相机无法工作/保存?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (175)

我正在尝试从Fragment...

如果我使用文件中的URI(Uri.fromFile(file)),在拍照并点击“ok”按钮(看起来无法写入URI或谁知道什么)之后,相机就不会退出。

使用FileString,以'/data/data/com.package.bla/cache/img198346262jpg'的形式,它不能正常工作(文件在那里,但是它是空的,因为相机没有在上面保存任何东西)。

到目前为止我尝试过的是:

  • 在创建文件后删除它。但是,在摄像机退出之后,文件就不存在了。
  • 添加了外部存储读取权限,以防万一。

因此,我不知道为什么映像没有被保存,并且已经花费/浪费了大量的时间来测试和弄清楚为什么它不能工作。

碎片:

private void launchCamera() {
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File outputDir = getActivity().getCacheDir();
    File file = null;
    try {
        file = File.createTempFile("img", "jpg", outputDir);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (file != null) {
        mImageUri = Uri.fromFile(file);   //using Uri is not even exiting the camera
        //mImageUri = File.toString();    //If I use String instead of an Uri, it works better (ie, can accept camera photo)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(cameraIntent, RESULT_TAKE_IMAGE);
    }
}


public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        Bitmap original = BitmapFactory.decodeFile(mImageUri.toString(), bounds);
    }
}

编辑的代码,mImageURI。如前所述,如果我使用URI,我甚至不能接受相机应用程序中的照片。使用字符串将允许我接受照片,尽管照片实际上没有保存(即文件中有0字节)。

解释问题与保存到缓存目录有关。可能是个bug,我缺少了一个权限,或者相机应用程序无法保存到您的应用程序私有数据目录中。添加权限标志FLAG_GRANT_WRITE_URI_PERMISSION解决不了这个问题。相关员额:将图像从摄像机存储到私有应用程序缓存目录通过意图将相机数据保存到缓存中

更新从android 2.2开始getExternalCacheDir()方法可以用来代替getCacheDir()

提问于
用户回答回答于
private String selectedImagePath = "";
    final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;

public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }


    public String getImagePath() {
        return imgPath;
    }

btnGallery.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);

            }
        });

        btnCapture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            }
        });

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == PICK_IMAGE) {
                selectedImagePath = getAbsolutePath(data.getData());
                imgUser.setImageBitmap(decodeFile(selectedImagePath));
            } else if (requestCode == CAPTURE_IMAGE) {
                selectedImagePath = getImagePath();
                imgUser.setImageBitmap(decodeFile(selectedImagePath));
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }

    }


public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }

public String getAbsolutePath(Uri uri) {
        String[] projection = { MediaColumns.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }
用户回答回答于

为什么不把它保存在一个新的文件中呢?

    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
    root.mkdirs();
    final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
    final File sdImageMainDirectory = new File(root, fname);
    mImageUri = Uri.fromFile(sdImageMainDirectory);

然后把uri传递给意图

    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);

扫码关注云+社区

领取腾讯云代金券