如何将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; }