【发布时间】:2014-08-13 16:11:58
【问题描述】:
我正在创建的应用程序需要从我们的服务器中提取一些图像,并显示在一个页面上。用户可以进入几个不同的类别,每个类别都有自己的图像。问题是在连续进入 2-3 个类别(取决于这些类别中有多少图像)后,应用程序没有更多内存,并且无法在不崩溃的情况下显示位图。
我希望能够在每次用户进入新类别时清除内存,以便旧类别的图像不再存储在内存中,从而为相关类别的图像腾出空间。我不确定这是否是一个好方法,或者如果是的话,我什至不确定如何去做。
如果有人有更好的解决方案,请告诉我。一个想法是一次只加载大约 20 张图片,并等到用户滚动到底部再加载更多图片,但是由于我们的客户付费将他们的图片放在应用程序上,这将导致某些图片的流量减少,所以这不是理想的解决方案。不过也不是没办法。
这是我用来加载图像的代码: 编辑:我的错误我发布了错误的代码,这是我正在使用的真实代码:
@SuppressWarnings("deprecation")
public Drawable loadImageFromWebOperations(String url, String imagePath) {
try {
if(Global.couponBitmaps.get(imagePath) != null){
scaledHeight = Global.couponBitmaps.get(imagePath).getHeight();
return new BitmapDrawable(getResources(), Global.couponBitmaps.get(imagePath));
}
Drawable d = null;
File f = new File(getBaseContext().getFilesDir().getPath().toString() + "/" + imagePath + ".png");
if (f.exists()) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int scaledWidth = 0;
try {
display.getSize(size);
scaledWidth = size.x;
} catch (java.lang.NoSuchMethodError ignore) {
scaledWidth = display.getWidth();
}
Bitmap bitmap = null;
BitmapScaler scaler = new BitmapScaler(f, scaledWidth);
bitmap = scaler.getScaled();
scaledHeight = bitmap.getHeight();
d = new BitmapDrawable(getResources(), bitmap);
Global.couponBitmaps.put(imagePath, bitmap);
} else {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int scaledWidth = 0;
try {
display.getSize(size);
scaledWidth = size.x;
} catch (java.lang.NoSuchMethodError ignore) {
scaledWidth = display.getWidth();
}
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url).getContent());
int height = bitmap.getHeight();
int width = bitmap.getWidth();
scaledHeight = (int) (((scaledWidth * 1.0) / width) * height);
f.getParentFile().mkdirs();
f.createNewFile();
OutputStream output = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, output);
output.close();
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false);
d = new BitmapDrawable(getResources(), bitmap);
Global.couponBitmaps.put(imagePath, bitmap);
}
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e){
e.printStackTrace();
return null;
}
}
如果有人知道是否有更有效的加载图像的方法,或者是否有在绘制之前清除内存的方法,将不胜感激,谢谢。
【问题讨论】:
标签: android image bitmap out-of-memory