您可以使用此方法对图像进行解码。它可能会使它们更轻。请记住,当图像显示增加内存消耗时,它们会变成位图。
public static Bitmap decode(byte[] imageByteArray, int width, int height) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length,
o);
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < width || height_tmp / 2 < height)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
o2.inTempStorage = new byte[Math.max(16 * 1024, width * height * 4)];
return BitmapFactory.decodeByteArray(imageByteArray, 0,
imageByteArray.length, o2);
// return BitmapFactory.decodeByteArray(imageByteArray, 0,
// imageByteArray.length);
}
在哪里
width - imageView 可能具有的最大宽度(以像素为单位)。
height - imageView 可能具有的最大像素高度。
这样,位图会变得更轻,应用程序可能会消耗更少的内存。
(注意:我复制了这个方法并稍微修改了一下,我不记得原来的问题所以我不能放网址)
我用来将图像存储在字节数组中,并且只在显示它们之前对其进行解码。
现在,就像 James L 所说的那样,最好将图像保存在文件系统中,并且只在需要时才带入内存,但如果你不这样做(我的情况)。您可以通过以下方式下载图片:
public static byte[] getBytes(InputStream is) throws IOException {
int len;
int size = 1024;
byte[] buf;
if (is instanceof ByteArrayInputStream) {
size = is.available();
buf = new byte[size];
len = is.read(buf, 0, size);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
buf = bos.toByteArray();
}
return buf;
}
public static byte[] downloadFileByteArray(String fileUrl)
throws IOException, MalformedURLException {
URL myFileUrl = null;
myFileUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
return getBytes(is);
}
如果您已经在内存中拥有图像,您将能够通过查看我提供的方法将它们转换为字节数组。
除此之外(并调用 System.gc()),您无能为力(据我所知)。如果需要,可能会在 onPause() 和 onDestroy() 中删除 BMP,并在 onResume() 中重新构建它们。