package com.matao.common.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by matao on 2016-12-23 10:54
 */

public class BitmapUtils {

    /**
     * 将任意图片压缩成 reqWidth * reqHeight 的缩略图
     *
     * @param res
     * @param resId
     * @param reqWidth  图片期望的宽度
     * @param reqHeight 图片期望的高度
     * @return  bitmap
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);
        return bitmap;
    }


    /**
     * 计算图片在期望宽高下的采样率
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return  inSampleSize
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            int halfWidth = width / 2;
            int halfHeight = height / 2;
            // 保证最终图片的宽和高一定都会大于等于目标的宽和高。
            // 此处采样率为最接近的一个2的整数次方。这是建议实现方式。
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}

@@ -386,17 +386,16 @@
 @return 
- 
 bitmap%0A 
@@ -627,16 +627,152 @@
 = true;%0A
+        // %E5%BD%93inJustDecodeBounds = true%E6%97%B6%EF%BC%8C%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%AE%A9%E8%A7%A3%E6%9E%90%E6%96%B9%E6%B3%95%E7%A6%81%E6%AD%A2%E4%B8%BAbitmap%E5%88%86%E9%85%8D%E5%86%85%E5%AD%98%EF%BC%8C%0A        // BitmapFactory.decodeResource%E8%BF%94%E5%9B%9E%E5%80%BC%E4%B9%9F%E4%B8%8D%E5%86%8D%E6%98%AF%E4%B8%80%E4%B8%AABitmap%E5%AF%B9%E8%B1%A1%EF%BC%8C%E8%80%8C%E6%98%AFnull, %E4%BD%86%E5%AE%BD%E9%AB%98%E4%BE%9D%E7%84%B6%E8%A2%AB%E8%B5%8B%E5%80%BC%0A
         
@@ -1178,17 +1178,16 @@
 @return 
- 
 inSample

Revise comment