Bitmap 图像解码以及缩略图生成----BitmapFactory类

如果一个内存比较大的图片加载在App上时会直接运行失败,所以要先通过解析生成一张缩略图
可以使用 BitmapFactory 类来解析 Bitmap 信息,解析过程可以先获取宽高,然后计算比例,然后解码像素信息
public static Bitmap decodeBitmap(String path, int maxWidth, int maxHeight) {
    // 配置转换的信息
    BitmapFactory.Options opts = new BitmapFactory.Options();
    // 只解析宽高,不解析内容
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, opts); // 得到到像素信息是 null ,但是可以得到图像的实际宽高
    // 分别计算宽度的比例和高度的比例
    int w = (int) Math.ceil(opts.outWidth / maxWidth);
    int h = (int) Math.ceil(opts.outHeight / maxHeight);
    if (w > 1 || h > 1) {
        // 该属性接收值必须要 >1  可以实现按照 1/opts.inSampleSize 的大小来解析该图片
        opts.inSampleSize = w > h ? w : h; 
    }
    opts.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
    return bitmap;
}

注意:最后要解析出像素信息必须要把 opts.inJustDecodeBounds 设置为 false 否则拿不到像素信息

public static void saveBitmap(Bitmap bitmap,String path){
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(path);
        // 保存 ( 压缩类型 , 压缩质量 , 输出流 )
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(null != out){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值