图片适配 压缩比例 (纯代码)

public class BitmapUtils {
    public static Bitmap decodeSampledBitmapFromResource(String  filePath,
            int reqWidth, int reqHeight) {

        //加载图片的边界信息(只读取图片的高度,宽度,不读取具体字节)
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options =
                new BitmapFactory.Options();
        //将此选项设置true,此时再加载图片就会只读取图片边界信息了。
        options.inJustDecodeBounds = true;
        //加载图片边界,并将边界信息封装到options对象
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize(计算压缩比例)
        options.inSampleSize =
        calculateInSampleSize(options,
        reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }
    /**计算压缩比例*/
    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    //获得实际图片的高度,宽度
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    //通过实际的高度,宽度与我们需要的高度,宽度进行比例运算得到一个压缩比例值
    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }
    return inSampleSize;//高度和宽度都按照此比例进行压缩
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值