Android平台Bitmap缓存为文件
来源:互联网 发布:s3c2410数据手册 编辑:程序博客网 时间:2024/06/05 16:41
如何将gif等图片格式在解析过程中解码得到的Bitmap转存为图片呢?Bitmap.java中提供了compress的方法,可以将Bitmap转换成文件,与BitmapFactory.java中的decodeStream方法相对应。下面是这两个方法的函数原型:
public static Bitmap decodeStream(InputStream is);public boolean compress(CompressFormat format, int quality, OutputStream stream);下面是FileUtils.java中的一段代码,先用decodeStream将系统res中的图片解码成Bitmap,然后再用compress转存为文件:
final File mf = new File(context.getFilesDir(), filename); if (!mf.exists()) { Bitmap bitmap = null; FileOutputStream fos = null; InputStream is = null; try { is = context.getResources().openRawResource(maskRawResourceId); bitmap = BitmapFactory.decodeStream(is); if (bitmap == null) { throw new IllegalStateException("Cannot decode raw resource mask"); } fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE); if (!bitmap.compress(CompressFormat.JPEG, 100, fos)) { throw new IllegalStateException("Cannot compress bitmap"); } } finally { if (is != null) { is.close(); } if (bitmap != null) { bitmap.recycle(); } if (fos != null) { fos.flush(); fos.close(); } } }那回到正题,如何将gif动画解析过程中的每帧图片缓存下来呢?方法如下:
private void bitmap2ImageFile(Bitmap bitmap, int index, int totalCount) { if ((index == totalCount - 1) || mSaveOnce) { mSaveOnce = true; return; } if (bitmap == null) { return; } String bitmapName = Environment.getExternalStorageDirectory().toString() + "/gif/" + index + ".png"; File f = new File(bitmapName); FileOutputStream fos = null; try { f.createNewFile(); fos = new FileOutputStream(f); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } finally { if (fos != null) { fos.flush(); fos.close(); } } }其中,参数bitmap为当前图片当前帧解码出来的Bitmap,index为当前帧索引号(从0起始),totalCount是gif动画的帧数。为了避免重复保存gif动画所有帧图片,加入变量boolean mSaveOnce,在保存完所有帧后,标志记为true,后面就不会再保存了。
另外,需要说明的是compress的第一个参数可支持以下几种格式:
public enum CompressFormat { JPEG (0), PNG (1), WEBP (2); CompressFormat(int nativeInt) { this.nativeInt = nativeInt; } final int nativeInt; }
- Android平台Bitmap缓存为文件
- android bitmap保存为文件及读取
- Android裁剪bitmap文件为正方形
- android 缓存Bitmap
- android 缓存Bitmap
- Android Bitmap 缓存
- android缓存Bitmap
- Android Bitmap 缓存策略
- Android 缓存大量 bitmap
- android bitmap 缓存 处理
- android中Bitmap对象怎么保存为文件?
- Android笔记(15)将bitmap存为文件
- android bitmap 怎么使用缓存?
- android bitmap 缓存工具类
- android bitmap缓存机制(上)
- android bitmap缓存机制(下)
- android: 缓存异步加载Bitmap
- Android中Bitmap缓存池
- JQuery validate ajax 表单验证方法。
- [Android实例] android实现顶级圆角弹窗(个人)
- 第十五章——抽象类,切片,多继承
- C++中float和double
- [LeetCode] Partition List
- Android平台Bitmap缓存为文件
- Reporting Service2008 匿名访问报表服务器2008配置
- Python 元组、列表、字典、文件
- 174977-2接插件及配套
- 高德地图中根据两点实现旋转图片的方法
- JAVA文件字节单位转换
- NPOI导出方法不依赖Office COM组件
- SQL Server2008附加数据库之后显示为只读时解决方法
- 关于nagios监控远程服务器对服务器性能影响的测试