德code文件从SD卡的Android以避免内存不足的错误,由于大的位图或setImageURI [英] Decode File From SdCard android to avoid out of memory error due to large bitmap or setImageURI
本文介绍了德code文件从SD卡的Android以避免内存不足的错误,由于大的位图或setImageURI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
避免outof内存错误从SD卡或从资源选择大的图像文件。 我怎样才能解决这个问题呢?
Avoid outof memory error for selecting large image file from sdcard or from resource. how can i tackle with this problem?
推荐答案
要避免错误,而从SD卡中选择文件中的位图或使用setImageURI到SD卡使用下面的方法:
To avoid error while selecting file from sd card in bitmap or using setImageURI to sdcard use following method:
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;
}
这篇关于德code文件从SD卡的Android以避免内存不足的错误,由于大的位图或setImageURI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文