Android图片工具类:获取Bitmap,压缩

本文介绍了一种将本地图片文件压缩至1M以下的方法,同时保持原图尺寸但会损失部分清晰度。通过调整JPEG压缩比例并循环检查压缩后的文件大小来实现目标。

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

获取本地图片的Bitmap

    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            BitmapFactory.Options options=new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inSampleSize = 1;//此参数为1表示质量不损失
            Bitmap btp =BitmapFactory.decodeStream(fis,null,options);
            return btp;  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }

    }

将本地图片文件压缩至1M以下,保持原尺寸,损失清晰度

    /**
     * compress img to less than 1M
     * @param bmp source Bitmap
     * @param file target File specified
     */
    public static void compressBmpToFile(Bitmap bmp,File file){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 99;//设置开始的compress系数
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();
            options -= 1;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值