【android】 如何把gif图片下载到本地
以上图片大家可以看到,虽然是个jpg格式的文件,但是本质上是个动图。
但是发现在咱的图片模块下,本地存储的图片只有一帧,问题出在哪里呢?
http获取到的byte[]数据是没问题的
断点跟踪了下,发现问题出现在最后一句压缩图片尺寸的时候。
public static Bitmap getScaledBitMap(byte[] data, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) inSampleSize = Math.round(srcHeight / height); else inSampleSize = Math.round(srcWidth / width); } options = new BitmapFactory.Options(); options.inSampleSize = inSampleSize; return BitmapFactory.decodeByteArray(data, 0, data.length, options); }
最后的解决之道是,不经过Bitmap,直接把http获取到的byte[]数据写入到本地;在取出的时候,才进行图片尺寸压缩。
/** * 写入bytes * * @param url * @param bytes * @return */ public boolean save(String url, byte[] bytes) { if (bytes == null || bytes.length == 0) return false; url = trans2Local(url); File file = new File(url); if (file.exists()) return true; ZIO.createNewFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(bytes); return true; } catch (Exception e) { e.printStackTrace(); Log.e("存储出错", e.getMessage()); } finally { try { fos.close(); } catch (Exception e) { e.printStackTrace(); } } return false; }
这种做法额外的好处是,不再理会奇怪的图片格式质量问题。
比如我们用Bitmap保存图片的时候还要取判断图片类型,还要去指定压缩精度(如果100的话图片尺寸比原图还要大很多,真奇怪)
Bitmap.CompressFormat format = url.toLowerCase().indexOf("png") > 0 ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
bitmap.compress(format, 75, fos);
分类:
Java基础知识
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端