Android中的图片压缩

本文介绍两种处理图片的方法:一是使用compress方法进行图片压缩,通过调整压缩比率确保图片大小不超过设定阈值;二是利用ThumbnailUtils提取指定尺寸的缩略图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种:通过compress

/**
     * 图片压缩
     * 
     * @param beforBitmap
     * @return
     */
    private Bitmap compressImage(Bitmap beforBitmap) {

        // 可以捕获内存缓冲区的数据,转换成字节数组。
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if (beforBitmap != null) {
            // 第一个参数:图片压缩的格式;第二个参数:压缩的比率;第三个参数:压缩的数据存放到bos中
            beforBitmap.compress(CompressFormat.JPEG, 100, bos);
            int options = 100;
            // 循环判断压缩后的图片是否是大于100kb,如果大于,就继续压缩,否则就不压缩
            while (bos.toByteArray().length / 1024 > 80) {
                bos.reset();// 置为空
                // 压缩options%
                beforBitmap.compress(CompressFormat.JPEG, options, bos);
                // 每次都减少10
                options -= 10;

            }
            // 从bos中将数据读出来 存放到ByteArrayInputStream中
            ByteArrayInputStream bis = new ByteArrayInputStream(
                    bos.toByteArray());
            // 将数据转换成图片
            Bitmap afterBitmap = BitmapFactory.decodeStream(bis);
            return afterBitmap;
        }
        return null;
    }

第二种:获取缩略图

/**
     * 获得缩略图
     * @param bitmap
     * @return
     */
    public Bitmap getThumbnail(Bitmap bitmap) {
        // 宽
        int w = bitmap.getWidth();
        // 高
        int h = bitmap.getHeight();
        // 获得缩略图
        Bitmap afterBitmap = ThumbnailUtils
                .extractThumbnail(bitmap, w, h);
        return afterBitmap;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值