gpt4 book ai didi

android - BitmapFactory.decodeFile 导致 outOfMemoryError

转载 作者:行者123 更新时间:2023-11-30 03:09:56 34 4
gpt4 key购买 nike

BitmapFactory.decodeFile 仅当我从手机图库中选择图像时才会导致 outOfMemoryError,而不是当我从使用相机 Intent 拍摄的照片中选择图像时。我实际上在使用相机 Intent 时避免使用 decodeFile。从图库中选择时我可以使用相同的方法(从 Intent 中获取数据)吗?这是我以两种方式获取图像的代码:

如果图片是从设备的图库中选择的:

if (requestCode == 1) 
{
if (intent != null && resultcode == RESULT_OK)
{
ImageHelper ih = new ImageHelper();
mProfilePicPath = ih.getSelectedImageFilePathFromGallery(this, intent);
Bitmap portraitPhoto = ih.getChosenImageFromGallery(mProfilePicPath);
try{
ih.saveImage("Profile pics", portraitPhoto, this);

ImageHelper.getChosenImageFromGallery:

public Bitmap getChosenImageFromGallery(String imagePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
options.inSampleSize = DressingRoomActivity.calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap portraitPhoto = ImageHelper.convertToPortraitOrientation(options, imagePath);
return portraitPhoto;
}

如果图像是通过使用相机拍照选择的:

else if ((requestCode == CAMERA_REQUEST)&& (resultcode == Activity.RESULT_OK)){
Bundle extras = intent.getExtras();
Uri selectedImage = intent.getData();
if (extras != null) {
ImageHelper ih = new ImageHelper();
mProfilePicPath = ih.getFilePathFromCameraPhoto(this, selectedImage);
Bitmap photo = (Bitmap) intent.getExtras().get("data");
try{
ih.saveImage("Profile pics", photo, this);

如您所见,要从图库中获取图像并从中获取位图,我必须使用此代码将位图创建为仅为 500 x 500 像素 options.inSampleSize = DressingRoomActivity.calculateInSampleSize(options , 500, 500); 否则它会在 Bitmap bmp = BitmapFactory.decodeFile(path, options); 行中导致 outOfMemoryError,它位于 ImageHelper.convertToPortraitOrientation(options, imagePath); 方法。这意味着用户从相机中获得其图像的原样质量,并从他们在图库中的图像中获得 500 像素的质量。

我的问题: 1) 有没有办法在从图库中选择时不让我的图像质量达到 500px?比如以某种方式避免这一行:Bitmap bmp = BitmapFactory.decodeFile(path, options); 或其他方式?

2) 对于画廊,我不得不转换为肖像,这只是一个小麻烦,但为什么呢?如果我不这样做,它会将照片横向翻转。

最佳答案

Here是关于如何 Display Bitmaps Efficiently 的完整教程来自官方文档。我和你有同样的问题。我所做的是在返回我的代码之前阅读并理解给定页面中的所有类(class)。试试看,您的头脑会更加清晰。

编辑

您的应用程序正在崩溃,因为您正在主线程中运行 Bitmap.decode() 方法。使用另一个线程(使用简单的 AsyncTask)来执行此操作。

正如我之前所说,有 a nice tuto on how to handle bitmap off UI Thread

关于android - BitmapFactory.decodeFile 导致 outOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21149179/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com