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);
            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);
    }

猜你喜欢

转载自blog.csdn.net/qq_27275851/article/details/101754218