如何从Uri中获得位图对象(如果我成功地将它存储在 /data/data/MYFOLDER/myimage.png或文件///data/data/MYFOLDER/myimage.png)在我的应用程序中使用它?
有人知道怎么做到吗?
如何从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);
点击这里查看答案
其他回答
MediaStore.Images.Media.getBitmap在API 29中已弃用。推荐的方法是使用ImageDecoder。在API 28中添加的createSource。
下面是如何获得位图:
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方向,媒体。getBitmap不
val bitmap = context.contentResolver.openInputStream(uri).use { data ->
BitmapFactory.decodeStream(data)
}
你需要打开输入流
使用
因为它会在操作完成后自动关闭流。
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,
)
通过使用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'