保存到图库后,Uri for Image无效

时间:2014-09-29 09:30:52

标签: android android-camera android-image

我让用户使用相机拍摄照片,然后将Bitmap保存到相应的库中:

private void letUserTakeUserTakePicture() {

    Intent pickIntent = new Intent();
    pickIntent.setType("image/*");
    pickIntent.setAction(Intent.ACTION_GET_CONTENT);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(getTempFile(getActivity())));

    String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
    Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
    chooserIntent.putExtra
            (Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePhotoIntent});

    startActivityForResult(chooserIntent, Values.REQ_CODE_TAKEPICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

      final File file = getTempFile(getActivity());              
      Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), Uri.fromFile(file));
      Uri uri = addImageToGallery(getActivity(), captureBmp, "herp", "derp"));          

}

private File getTempFile(Context context) {

    if (tempFile !=  null) {
        return tempFile;
    }

    final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
    if (!path.exists()) {
        path.mkdir();
    }

    tempFile = new File(path, "image.tmp");

    return tempFile;
}

private Uri addImageToGallery(Context context, Bitmap bitmap, String title, String description) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, title);
    values.put(MediaStore.Images.Media.DESCRIPTION, description);
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

    MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, title, description);
    return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}

图像保存到图库就好了。我收到一个看起来像这样的Uri:

content://media/external/images/media/125

但是当我将此URI传递给UniversalImageLoader的实例时,它无法找到图像(java.io.FileNotFoundException)虽然我知道UIL可以处理这种Uris(工作得很好)如果我让用户从图库中选择一个图像)。

我对如何抓住我保存到画廊的图像感到困惑,所以我可以显示它,而且我不会在我尝试的时候越来越困惑。

任何帮助表示赞赏,我做错了什么?

编辑:Pr38y的评论是对的,错误发生在addImageToGallery()方法中,我试图插入两次相同的imange。

谢谢!

0 个答案:

没有答案