Android平臺Bitmap緩存爲文件

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章