如何从Uri中获得位图对象(如果我成功地将它存储在 /data/data/MYFOLDER/myimage.png或文件///data/data/MYFOLDER/myimage.png)在我的应用程序中使用它?

有人知道怎么做到吗?


当前回答

ContentResolver cr = context.getContentResolver();
try (InputStream input = cr.openInputStream(url)) {
    Bitmap bitmap = BitmapFactory.decodeStream(input);
}

其他回答

ContentResolver cr = context.getContentResolver();
try (InputStream input = cr.openInputStream(url)) {
    Bitmap bitmap = BitmapFactory.decodeStream(input);
}
  InputStream imageStream = null;
    try {
        imageStream = getContext().getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

在2022年使用线圈库。

https://coil-kt.github.io/coil/compose/

对于喷气背包组合

            AsyncImage(
                model = uriOfImage,
                contentDescription = null,
            )

下面是正确的做法:

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);
    }
}

如果你需要加载非常大的图像,下面的代码将以tile的形式加载它(避免大的内存分配):

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

点击这里查看答案

我已经尝试了很多方法。这对我来说非常合适。

如果你从图库中选择图片。你需要注意从intent获取Uri。剪切数据或意图。数据,因为其中一个在不同的版本中可能为空。

  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 )
}