如何在Android中使用位图时避免出现内存不足错误 [英] How to avoid an out of memory error while using bitmaps in Android
问题描述
我正在使用位图.代码运行时显示内存不足错误.如何避免错误.我的代码如下.预先感谢.
I am using bitmaps. When the code runs it shows an out of memory error. How can the error be avoided. My code follows. Thanks in advance.
Bitmap myBitmap = Image.decodeSampledBitmapFromUri(path, 250, 500);
img_cook[index].setImageBitmap(myBitmap);
public static Bitmap decodeSampledBitmapFromUr(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
推荐答案
使用位图完成后,意味着当位图完成其工作后,将其设为Recyle和null,如下所示:
When you have done with your Bitmap, means when your Bitmap done its work then make it recyle and null like below:
bitmap.recycle();
bitmap=null;
或
我认为您是从url下载图片,因此建议您使用Android Query,如果您使用它,将永远不会收到此错误.
I think you are downloading Image from url, so I am suggesting you to use Android Query for this, you will never get this error if you used it.
您可以从此处下载jar文件: http://code.google.com/p/android-query/downloads/list 下载jar文件并将jar设置为您的构建路径.
You can download the jar file from here : http://code.google.com/p/android-query/downloads/list Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
以直接从url加载图像为例:
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
从网址获取位图的示例:
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
@Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
它非常快速且准确,使用它您可以在加载时找到更多功能,例如动画";获取位图(如果需要);等
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
这篇关于如何在Android中使用位图时避免出现内存不足错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!