【达内课程】Bitmap图片的压缩

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010356768/article/details/83016046

在这里插入图片描述

BitmapUtils

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BitmapUtils {

    /**
     * 压缩图片,获取相应尺寸的图片
     * @param is 输入流
     * @param width 目标宽度
     * @param height 目标高度
     * @return
     */
    public static Bitmap loadBitmap(InputStream is,int width,int height) throws IOException {
        //把is解析,把数据读取到byte[]中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //把输入流中的数据读取到bos中
        byte[] buffer = new byte[1024*8];
        int length = 0;
        while ((length=is.read(buffer))!=-1){
            bos.write(buffer,0,length);
            bos.flush();
        }
        //该byte数组描述的是一个图片的完整信息
       byte[] bytes = bos.toByteArray();
        //获取图片原始尺寸
        BitmapFactory.Options options = new BitmapFactory.Options();
        //仅仅加载边界属性
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
        //根据原始尺寸和width、height计算压缩比例
        int w = options.outWidth/width;
        int h = options.outHeight/height;
        int scale = w>h?w:h;
        //执行压缩
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;//设置缩放比例
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
        return bitmap;
    }
}

使用

Bitmap bitmap = BitmapUtils.loadBitmap(is,5,5);

猜你喜欢

转载自blog.csdn.net/u010356768/article/details/83016046