Thumbnails压缩图片到指定大小

网上看了很多demo,很多都是照搬别人的代码,不管有没有问题,有的甚至递归不关流,还有的递归疯狂往自己磁盘写文件,递归一次写一次,我自己把网上的demo整理改了下发出来。

 /** 
    * @Description: 压缩图片到指定大小
    * @Param:  desFileSize:大小,accuracy:每次缩小几倍
    * @return:  String 
    * @Author: zzy 
    * @Date: 2019/9/29 
    */ 
    public static String commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
        long srcFileSizeJPG = bytes.length;
        System.out.println(srcFileSizeJPG);
        // 2、判断大小,如果小于,不压缩;如果大于等于,压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
  		    File file=new File("D://img/abc.png");
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.close();;            
            return ImageToBase64(bytes);
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                new BigDecimal(accuracy)).intValue();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        byte[] bytes1 = baos.toByteArray();
        baos.close();
        return commpressPicCycle(bytes1, desFileSize, accuracy);
    }

图片转base64


 /**
     * @Description: 图片转base64编码
     * @Param:
     * @return:
     * @Author: zzy
     * @Date: 2019/9/29
     */
    public static String ImageToBase64(byte[] imgByte) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(imgByte);// 返回Base64编码过的字节数组字符串
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值