1:加载网络图片采用如下方法的时候。
bitmap = BitmapFactory.decodeStream(uc.getInputStream());
解决方法:先讲图像加载到本地
public static Bitmap loadBitmapFromLocal(String localPath, boolean isCache) { if(localPath == null){ return null; } File file = new File(localPath); // 如果缓存图片存在,则返回 if (file.exists()) { Log.d(TAG, "【本地】加载..." + localPath); if (BitmapManager.containsKey(localPath)) { return BitmapManager.get(localPath); } else { try { String path = file.getAbsolutePath(); Bitmap bmp = BitmapFactory.decodeFile(path); if (isCache && bmp != null) { BitmapManager.put(localPath, bmp); } return bmp; } catch (OutOfMemoryError err) { err.printStackTrace(); } } } return null;
解决方法:先讲图像加载到本地
然后
bmp = loadBitmapFromLocal(fileWholePath, false);附上源码
String fileName = linkUrl.substring((linkUrl.lastIndexOf("/")+1)); String fileWholePath = getCachePath(fileName); BufferedOutputStream fout = new BufferedOutputStream( new FileOutputStream(new File(fileWholePath))); InputStream in = uc.getInputStream(); byte[] data = new byte[1024 * 5]; int len = 0; while((len = in.read(data)) != -1){ fout.write(data, 0, len); } fout.flush(); //放倒while循环的外面 fout.close(); in.close();public static Bitmap loadBitmapFromLocal(String localPath, boolean isCache) { if(localPath == null){ return null; } File file = new File(localPath); // 如果缓存图片存在,则返回 if (file.exists()) { Log.d(TAG, "【本地】加载..." + localPath); if (BitmapManager.containsKey(localPath)) { return BitmapManager.get(localPath); } else { try { String path = file.getAbsolutePath(); Bitmap bmp = BitmapFactory.decodeFile(path); if (isCache && bmp != null) { BitmapManager.put(localPath, bmp); } return bmp; } catch (OutOfMemoryError err) { err.printStackTrace(); } } } return null;
本文详细阐述了在网络应用中加载图片时遇到的问题,并提供了解决方案:通过将图片加载到本地并进行缓存,从而提高加载速度和用户体验。文章包括关键步骤如从URL获取文件名、构建本地路径、读取网络流到本地文件,以及如何从本地加载已缓存的图片。同时,还讨论了内存溢出错误的处理。
3095

被折叠的 条评论
为什么被折叠?



