250

如何从 Uri 中获取 Bitmap 对象(如果我成功将其存储在 /data/data/MYFOLDER/myimage.png或中file///data/data/MYFOLDER/myimage.png)以在我的应用程序中使用它?

有谁知道如何做到这一点?

4

19 回答 19

619

Here's the correct way of doing it:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

See the answer here

于 2011-01-17T20:48:15.287 回答
122

这是正确的做法,同时也密切关注内存使用情况:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode == RESULT_OK)
  {
    Uri imageUri = data.getData();
    Bitmap bitmap = getThumbnail(imageUri);
  }
}

public static Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
  InputStream input = this.getContentResolver().openInputStream(uri);

  BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
  onlyBoundsOptions.inJustDecodeBounds = true;
  onlyBoundsOptions.inDither=true;//optional
  onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
  BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
  input.close();

  if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
    return null;
  }

  int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

  double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;

  BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
  bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
  bitmapOptions.inDither = true; //optional
  bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//
  input = this.getContentResolver().openInputStream(uri);
  Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
  input.close();
  return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio){
  int k = Integer.highestOneBit((int)Math.floor(ratio));
  if(k==0) return 1;
  else return k;
}

Mark Ingram 帖子中的 getBitmap() 调用也调用了 decodeStream(),因此您不会丢失任何功能。

参考:

于 2011-06-03T14:13:47.070 回答
48
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e) 
{
    //handle exception
}

是的,路径必须是这样的格式

file:///mnt/sdcard/filename.jpg

于 2013-09-13T11:24:13.763 回答
47

似乎MediaStore.Images.Media.getBitmap已在API 29. 推荐的方式是使用ImageDecoder.createSourcewhich was added in API 28

以下是获取位图的方法:

val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
} else {
    MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
}

重要提示:ImageDecoder.decodeBitmap阅读 EXIF 方向,Media.getBitmap

于 2019-09-19T09:53:08.233 回答
23
private void uriToBitmap(Uri selectedFileUri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(selectedFileUri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);

        parcelFileDescriptor.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
于 2015-08-27T15:12:29.640 回答
21

这是最简单的解决方案:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
于 2018-05-28T17:26:14.673 回答
11

您可以像这样从 uri 检索位图

Bitmap bitmap = null;
try {
    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
    e.printStackTrace();
}
于 2018-04-27T06:50:04.340 回答
11
Uri imgUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imgUri);
于 2018-08-02T10:58:13.513 回答
3
  InputStream imageStream = null;
    try {
        imageStream = getContext().getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
于 2020-02-05T12:16:27.203 回答
3
private fun setImage(view: ImageView, uri: Uri) {
        val stream = contentResolver.openInputStream(uri)
        val bitmap = BitmapFactory.decodeStream(stream)
        view.setImageBitmap(bitmap)
}
于 2021-01-30T14:18:00.673 回答
2

现在已贬低其中的插图getBitmap我在 Kotlin 中使用以下方法

PICK_IMAGE_REQUEST ->
    data?.data?.let {
        val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(it))
        imageView.setImageBitmap(bitmap)
    }
于 2020-01-06T19:58:12.127 回答
2

你可以这样做:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    Bundle extras = imageReturnedIntent.getExtras();
                    bitmap = extras.getParcelable("data");
            }
            break;
   }

通过这个,您可以轻松地将 uri 转换为位图。希望能帮助你。

于 2017-06-20T15:16:15.650 回答
2

使用 startActivityForResult 方法,如下所示

        startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);

你可以得到这样的结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    switch (requestCode) {
        case PICK_IMAGE:
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
         break;
    }
}
于 2017-07-11T10:28:41.010 回答
2

我尝试了很多方法。这对我来说很完美。

如果您从图库中选择图片。您需要注意Uriintent.clipdataor获取intent.data,因为其中一个在不同版本中可能为 null。

  private fun onChoosePicture(data: Intent?):Bitmap {
        data?.let {
            var fileUri:Uri? = null

              data.clipData?.let {clip->
                  if(clip.itemCount>0){
                      fileUri = clip.getItemAt(0).uri
                  }
              }
            it.data?.let {uri->
                fileUri = uri
            }


               return MediaStore.Images.Media.getBitmap(this.contentResolver, fileUri )
}
于 2020-06-10T13:19:21.703 回答
1

(KOTLIN) 因此,截至 2020 年 4 月 7 日,上述选项均无效,但以下是对我有用的方法:

  1. 如果要将位图存储在 val 中并使用它设置 imageView,请使用以下命令:

    val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

  2. 如果您只想将位图设置为和 imageView,请使用以下命令:

    BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

于 2020-04-07T05:02:28.407 回答
1
* For getting bitmap from uri. Work for me perfectly.
    
    
    public static Bitmap decodeUriToBitmap(Context mContext, Uri sendUri) {
          Bitmap getBitmap = null;
          try {
            InputStream image_stream;
            try {
              image_stream = mContext.getContentResolver().openInputStream(sendUri);
              getBitmap = BitmapFactory.decodeStream(image_stream);
            } catch (FileNotFoundException e) {
              e.printStackTrace();
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
          return getBitmap;
        }
于 2021-04-04T08:53:52.187 回答
1

通过使用 glide 库,您可以从中获取位图uri

几乎在三星设备图像旋转时,我们必须使用检查旋转exifinterface

但使用 glide 无需检查旋转,图像总是正确接收。

在科特林你可以bitmap得到

CoroutineScope(Dispatchers.IO).launch {
   var bitmap = Glide.with(context).asBitmap().load(imageUri).submit().get()//this is synchronous approach                  
}

我正在使用这个依赖

api 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
于 2021-06-18T05:34:47.670 回答
0

从移动图库获取图像 uri 的完整方法。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();

     try { //Getting the Bitmap from Gallery
           Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
           rbitmap = getResizedBitmap(bitmap, 250);//Setting the Bitmap to ImageView
           serImage = getStringImage(rbitmap);
           imageViewUserImage.setImageBitmap(rbitmap);
      } catch (IOException e) {
           e.printStackTrace();
      }


   }
}
于 2017-11-25T14:06:01.847 回答
0
ContentResolver cr = context.getContentResolver();
try (InputStream input = cr.openInputStream(url)) {
    Bitmap bitmap = BitmapFactory.decodeStream(input);
}
于 2021-08-20T11:53:15.487 回答