Java 将图像加载到位图并获取OutOfMemoryError异常
我想像instagram一样加载很多图像,但我的代码仍然可以一次加载18个图像,并且可以向下滚动加载更多图像。 我还将图像缓存到磁盘,并在加载到位图之前调整图像大小以适应缩略图Java 将图像加载到位图并获取OutOfMemoryError异常,java,android,caching,bitmap,out-of-memory,Java,Android,Caching,Bitmap,Out Of Memory,我想像instagram一样加载很多图像,但我的代码仍然可以一次加载18个图像,并且可以向下滚动加载更多图像。 我还将图像缓存到磁盘,并在加载到位图之前调整图像大小以适应缩略图 private Bitmap loadBitmap(String id) throws IOException{ String key = id.toLowerCase(); // Check disk cache in background thread Bit
private Bitmap loadBitmap(String id) throws IOException{
String key = id.toLowerCase();
// Check disk cache in background thread
Bitmap image = cacher.get(key);
if (image == null){
// Not found in disk cache
// Process as normal
if(!isCancelled()){
//download image to stream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DriveApiActivity.getService().files().get(id)
.executeMediaAndDownloadTo(stream);
//decode image to byte array
byte[] byteArray = stream.toByteArray();
stream.close();
//decode byte array to bitmap file
image = decodeToBitmap(
byteArray,
CustomCardView.width,
CustomCardView.height);
// Add final bitmap to caches
cacher.put(key, image);
}
}
return image;
}
Logcat说异常来自cacher.get()方法
此代码来自谷歌提供的您必须使用:
largeheap = true
在android中。清单文件,从这一行您无法获取内存不足错误
这将解决您的问题有许多图像加载库,为什么不使用这些库?如果您真的想将大量图像加载到内存中,很可能会遇到内存问题。不要试图处理图像加载你自己,考虑使用一个库,e.i. picasso(),然后使用这个加载图像:<代码> Picasso。http://path/to/image.png)。将()装入(imageView)代码>这将减少加载位图的大小,并可能节省大量内存。我想练习处理缓存和内存。我不知道这是否困难
largeheap = true