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

有人知道怎么做到吗?


当前回答

下面是正确的做法:

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

点击这里查看答案

其他回答

(芬兰湾的科特林) 所以,截至2020年4月7日,上述选项都没用,但以下是对我有效的:

如果你想在val中存储位图,并设置一个imageView,使用这个: val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also {bitmap -> imageView.setImageBitmap(bitmap)} 如果你只是想设置位图为和imageView,使用这个: BitmapFactory.decodeFile(currentPhotoPath).also {bitmap -> imageView.setImageBitmap(bitmap)}

Bitmap bitmap = null;
ContentResolver contentResolver = getContentResolver(); 
try {
    if(Build.VERSION.SDK_INT < 28) {
        bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
    } else {
        ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, imageUri);
        bitmap = ImageDecoder.decodeBitmap(source);
    }
} catch (Exception e) {
    e.printStackTrace();
}
private fun setImage(view: ImageView, uri: Uri) {
        val stream = contentResolver.openInputStream(uri)
        val bitmap = BitmapFactory.decodeStream(stream)
        view.setImageBitmap(bitmap)
}
* 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;
        }

你可以这样做:

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转换为位图。 希望能帮助你。