图片内存溢出总结

本文详细阐述了在网络应用中加载图片时遇到的问题,并提供了解决方案:通过将图片加载到本地并进行缓存,从而提高加载速度和用户体验。文章包括关键步骤如从URL获取文件名、构建本地路径、读取网络流到本地文件,以及如何从本地加载已缓存的图片。同时,还讨论了内存溢出错误的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:加载网络图片采用如下方法的时候。

bitmap = BitmapFactory.decodeStream(uc.getInputStream());
解决方法:先讲图像加载到本地

然后

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值