谷歌推薦使用方法,從資源中加載圖像,並高效壓縮,有效降低OOM的概率

讀書筆記

/**
     * 谷歌推薦使用方法,從資源中加載圖像,並高效壓縮,有效降低OOM的概率
     * @param res 資源
     * @param resId 圖像資源的資源id
     * @param reqWidth 要求圖像壓縮後的寬度
     * @param reqHeight 要求圖像壓縮後的高度
     * @return
     */
    public Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        // 設置inJustDecodeBounds = true ,表示獲取圖像信息,但是不將圖像的像素加入內存
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // 調用方法計算合適的 inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // inJustDecodeBounds 置爲 false 真正開始加載圖片
        options.inJustDecodeBounds = false;
        //將options.inPreferredConfig改成Bitmap.Config.RGB_565,
        // 是默認情況Bitmap.Config.ARGB_8888佔用內存的一般
        options.inPreferredConfig= Bitmap.Config.RGB_565;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    // 計算 BitmapFactpry 的 inSimpleSize的值的方法
    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        if (reqWidth == 0 || reqHeight == 0) {
            return 1;
        }

        // 獲取圖片原生的寬和高
        final int height = options.outHeight;
        final int width = options.outWidth;
        Log.d(TAG, "origin, w= " + width + " h=" + height);
        int inSampleSize = 1;

        // 如果原生的寬高大於請求的寬高,那麼將原生的寬和高都置爲原來的一半
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 主要計算邏輯
            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        Log.d(TAG, "sampleSize:" + inSampleSize);
        return inSampleSize;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章