简体   繁体   English

使用uri将图像加载到位图

[英]Loading image into bitmap with uri

At first, I get path to image from user's gallery, like that:首先,我从用户的图库中获取图像的路径,如下所示:

@Override 
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent imageReturnedIntent) { 
 super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
 
 switch (requestCode){ 
 case Pick_image: 
 if(resultCode == RESULT_OK){ 
 try { 
 final Uri imageUri = imageReturnedIntent.getData(); 
 final InputStream imageStream = getContentResolver().openInputStream(imageUri); 
 
 pathToImage = imageUri.toString(); 
 choosePath.setImageResource(R.drawable.ic_check); 
 } catch (FileNotFoundException e){ 
 e.printStackTrace(); 
 } 
 } 
 } 
 }

And save it to Database, for example: "content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FDCIM%2FCamera%2FIMG_20210522_105740.jpg", I have xiaomi device.并将其保存到数据库,例如:“content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FDCIM%2FCamera%2FIMG_20210522_105740.jpg”,我有小米设备。 Then in other Activity I need get this image, I do it like that:然后在其他活动中我需要得到这个图像,我这样做:

bitmap = BitmapFactory.decodeFile(favouriteTemplates.get(position).getImageLink()); 
 holder.icon.setImageBitmap(bitmap);

Where "favouriteTemplates.get(position).getImageLink" is my path.其中“favouriteTemplates.get(position).getImageLink”是我的路径。 But decodeFile returns null and my ImageView remains empty, although my LogCat doesnt show any exceptions但是 decodeFile 返回 null 并且我的 ImageView 保持为空,尽管我的 LogCat 没有显示任何异常

Try with the following code you do not need to convert into bitmap you can also display image on imageView using imageUri.尝试使用以下代码,您不需要转换为位图,您也可以使用 imageUri 在 imageView 上显示图像。

String imageUri = favouriteTemplates.get(position).getImageLink();
holder.icon.setImageURI(imageUri)

//Use this for bitmap
Bitmap bitmap = 
MediaStore.Images.Media.getBitmap(this.getContentResolver(), 
imageUri);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM