Android圖片緩存之Bitmap詳解

Bitmap:

     Bitmap是Android系統中的圖像處理的最重要類之一。用它可以獲取圖像文件信息,進行圖像剪切、旋轉、縮放等操作,並可以指定格式保存圖像文件。

 重要函數

  •  public void recycle() // 回收位圖佔用的內存空間,把位圖標記爲Dead

  •  public final boolean isRecycled() //判斷位圖內存是否已釋放  

  •  public final int getWidth()//獲取位圖的寬度 

  •  public final int getHeight()//獲取位圖的高度

  •  public final boolean isMutable()//圖片是否可修改 

  •  public int getScaledWidth(Canvas canvas)//獲取指定密度轉換後的圖像的寬度 

  •  public int getScaledHeight(Canvas canvas)//獲取指定密度轉換後的圖像的高度 

  • public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的圖片格式以及畫質,將圖片轉換爲輸出流。 

    format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 

    quality:畫質,0-100.0表示最低畫質壓縮,100以最高畫質壓縮。對於PNG等無損格式的圖片,會忽略此項設置。

  • public static Bitmap createBitmap(Bitmap src) //以src爲原圖生成不可變得新圖像 

  • public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src爲原圖,創建新的圖像,指定新圖像的高寬以及是否可變。 

  • public static Bitmap createBitmap(int width, int height, Config config)——創建指定格式、大小的位圖 

  • public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source爲原圖,創建新的圖片,指定起始座標以及新圖像的高寬。

BitmapFactory工廠類:

    Option 參數類:
  • public boolean inJustDecodeBounds//如果設置爲true,不獲取圖片,不分配內存,但會返回圖片的高度寬度信息。

  • public int inSampleSize//圖片縮放的倍數

  • public int outWidth//獲取圖片的寬度值

  • public int outHeight//獲取圖片的高度值 

  • public int inDensity//用於位圖的像素壓縮比 

  • public int inTargetDensity//用於目標位圖的像素壓縮比(要生成的位圖) 

  • public byte[] inTempStorage //創建臨時文件,將圖片存儲

  • public boolean inScaled//設置爲true時進行圖片壓縮,從inDensity到inTargetDensity

  • public boolean inDither //如果爲true,解碼器嘗試抖動解碼

  • public Bitmap.Config inPreferredConfig //設置解碼器

  • public String outMimeType //設置解碼圖像

  • public boolean inPurgeable//當存儲Pixel的內存空間在系統內存不足時是否可以被回收

  • public boolean inInputShareable //inPurgeable爲true情況下才生效,是否可以共享一個InputStream

  • public boolean inPreferQualityOverSpeed  //爲true則優先保證Bitmap質量其次是解碼速度

  • public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔幾個像素加一條線段

  • public int inScreenDensity //當前屏幕的像素密度

  工廠方法:
  • public static Bitmap decodeFile(String pathName, Options opts) //從文件讀取圖片 

  • public static Bitmap decodeFile(String pathName)

  • public static Bitmap decodeStream(InputStream is) //從輸入流讀取圖片

  • public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)

  • public static Bitmap decodeResource(Resources res, int id) //從資源文件讀取圖片

  • public static Bitmap decodeResource(Resources res, int id, Options opts) 

  • public static Bitmap decodeByteArray(byte[] data, int offset, int length) //從數組讀取圖片

  • public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)

  • public static Bitmap decodeFileDescriptor(FileDescriptor fd)//從文件讀取文件 與decodeFile不同的是這個直接調用JNI函數進行讀取 效率比較高

  • public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)

  Bitmap.Config inPreferredConfig :

     枚舉變量 (位圖位數越高代表其可以存儲的顏色信息越多,圖像越逼真,佔用內存越大)

  • public static final Bitmap.Config ALPHA_8 //代表8位Alpha位圖        每個像素佔用1byte內存
  • public static final Bitmap.Config ARGB_4444 //代表16位ARGB位圖  每個像素佔用2byte內存
  • public static final Bitmap.Config ARGB_8888 //代表32位ARGB位圖  每個像素佔用4byte內存
  • public static final Bitmap.Config RGB_565 //代表8位RGB位圖          每個像素佔用2byte內存
     Android中一張圖片(BitMap)佔用的內存主要和以下幾個因數有關:圖片長度,圖片寬度,單位像素佔用的字節數。一張圖片(BitMap)佔用的內存=圖片長度*圖片寬度*單位像素佔用的字節數

圖片讀取實例:

   1.)從文件讀取方式一

/**
     * 獲取縮放後的本地圖片
     *
     * @param filePath 文件路徑
     * @param width    寬
     * @param height   高
     * @return
     */
    public static Bitmap readBitmapFromFile(String filePath, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, 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.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeFile(filePath, options);
    }

 2.)從文件讀取方式二 效率高於方式一
/**
     * 獲取縮放後的本地圖片
     *
     * @param filePath 文件路徑
     * @param width    寬
     * @param height   高
     * @return
     */
    public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) {
        try {
            FileInputStream fis = new FileInputStream(filePath);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fis.getFD(), null, 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.inJustDecodeBounds = false;
            options.inSampleSize = inSampleSize;

            return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
        } catch (Exception ex) {
        }
        return null;
    }

測試同樣生成10張圖片兩種方式耗時比較 cpu使用以及內存佔用兩者相差無幾 第二種方式效率高一點 所以建議優先採用第二種方式

start = System.currentTimeMillis();
        for (int i = 0; i < testMaxCount; i++) {
            BitmapUtils.readBitmapFromFile(filePath, 400, 400);
        }
        end = System.currentTimeMillis();
        Log.e(TAG, "BitmapFactory decodeFile--time-->" + (end - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < testMaxCount; i++) {
           BitmapUtils.readBitmapFromFileDescriptor(filePath, 400, 400);
        }
        end = System.currentTimeMillis();
        Log.e(TAG, "BitmapFactory decodeFileDescriptor--time-->" + (end - start));


3.)從輸入流中讀取文件

/**
     * 獲取縮放後的本地圖片
     *
     * @param ins    輸入流
     * @param width  寬
     * @param height 高
     * @return
     */
    public static Bitmap readBitmapFromInputStream(InputStream ins, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(ins, null, 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.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeStream(ins, null, options);
    }

4.)從資源文件中讀取文件 
public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resourcesId, 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.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeResource(resources, resourcesId, options);
    }

 此種方式相當的耗費內存 建議採用decodeStream代替decodeResource 可以如下形式
public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {
        InputStream ins = resources.openRawResource(resourcesId);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(ins, null, 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.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeStream(ins, null, options);
    }

decodeStream、decodeResource佔用內存對比:
start = System.currentTimeMillis();
        for (int i = 0; i < testMaxCount; i++) {
            BitmapUtils.readBitmapFromResource(getResources(), R.mipmap.ic_app_center_banner, 400, 400);
            Log.e(TAG, "BitmapFactory decodeResource--num-->" + i);
        }
        end = System.currentTimeMillis();
        Log.e(TAG, "BitmapFactory decodeResource--time-->" + (end - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < testMaxCount; i++) {
            BitmapUtils.readBitmapFromResource1(getResources(), R.mipmap.ic_app_center_banner, 400, 400);
            Log.e(TAG, "BitmapFactory decodeStream--num-->" + i);
        }
        end = System.currentTimeMillis();
        Log.e(TAG, "BitmapFactory decodeStream--time-->" + (end - start));

BitmapFactory.decodeResource 加載的圖片可能會經過縮放,該縮放目前是放在 java 層做的,效率比較低,而且需要消耗 java 層的內存。因此,如果大量使用該接口加載圖片,容易導致OOM錯誤

BitmapFactory.decodeStream 不會對所加載的圖片進行縮放,相比之下佔用內存少,效率更高。

這兩個接口各有用處,如果對性能要求較高,則應該使用 decodeStream;如果對性能要求不高,且需要 Android 自帶的圖片自適應縮放功能,則可以使用 decodeResource。

5. )從二進制數據讀取圖片
public static Bitmap readBitmapFromByteArray(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.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeByteArray(data, 0, data.length, options);
    }

6.)從assets文件讀取圖片
/**
     * 獲取縮放後的本地圖片
     *
     * @param filePath 文件路徑
     * @return
     */
    public static Bitmap readBitmapFromAssetsFile(Context context, String filePath) {
        Bitmap image = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(filePath);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

圖片保存文件:

public static void writeBitmapToFile(String filePath, Bitmap b, int quality) {
        try {
            File desFile = new File(filePath);
            FileOutputStream fos = new FileOutputStream(desFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            b.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

圖片壓縮:

 private static Bitmap compressImage(Bitmap image) {
        if (image == null) {
            return null;
        }
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] bytes = baos.toByteArray();
            ByteArrayInputStream isBm = new ByteArrayInputStream(bytes);
            Bitmap bitmap = BitmapFactory.decodeStream(isBm);
            return bitmap;
        } catch (OutOfMemoryError e) {
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }

圖片縮放:

/**
     * 根據scale生成一張圖片
     *
     * @param bitmap
     * @param scale  等比縮放值
     * @return
     */
    public static Bitmap bitmapScale(Bitmap bitmap, float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale); // 長和寬放大縮小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

獲取圖片旋轉角度:

/**
     * 讀取照片exif信息中的旋轉角度
     *
     * @param path 照片路徑
     * @return角度
     */
    private static int readPictureDegree(String path) {
        if (TextUtils.isEmpty(path)) {
            return 0;
        }
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (Exception e) {
        }
        return degree;
    }

更多內容,請看這裏:http://www.cnblogs.com/whoislcj/p/5547758.html






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