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

有人知道怎么做到吗?


当前回答

我没有看到正确答案,所以我把这个扩展写在这里

fun Context.getBitmap(uri: Uri): Bitmap =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.contentResolver, uri))
    else MediaStore.Images.Media.getBitmap(this.contentResolver, uri)

代码示例:

val bitmap = context.getBitmap(uri)

提示:你也可以更新活动/片段的扩展,所以你不需要 根本不需要写上下文。再加一点合成糖)

其他回答

从移动库中获取图像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();
      }


   }
}

你可以像这样从uri中检索位图

Bitmap bitmap = null;
try {
    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
    e.printStackTrace();
}

我没有看到正确答案,所以我把这个扩展写在这里

fun Context.getBitmap(uri: Uri): Bitmap =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.contentResolver, uri))
    else MediaStore.Images.Media.getBitmap(this.contentResolver, uri)

代码示例:

val bitmap = context.getBitmap(uri)

提示:你也可以更新活动/片段的扩展,所以你不需要 根本不需要写上下文。再加一点合成糖)

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

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

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

但使用滑动不需要检查旋转,图像总是正确接收。

在kotlin你可以得到位图作为

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'