gpt4 book ai didi

android - 从 SdCard android 解码文件以避免由于大位图或 setImageURI 而导致内存不足错误

转载 作者:太空狗 更新时间:2023-10-29 15:31:19 25 4
gpt4 key购买 nike

避免从 SD 卡或资源中选择大图像文件时出现内存不足错误。我该如何解决这个问题?

最佳答案

为避免在位图中从 sd 卡中选择文件或使用 setImageURI 到 sdcard 时出错,请使用以下方法:

public static Bitmap decodeScaledBitmapFromSdCard(String filePath,
int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}

public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

关于android - 从 SdCard android 解码文件以避免由于大位图或 setImageURI 而导致内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15377186/

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