图片压缩工具

首先引入依赖

 <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.4</version>
        </dependency>
        <!--图片压缩-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

如下代码实现:


byte[] bytes = ImgUtil.scalePic(file, 0.5);
// byte[] scalePicLater = ImgUtil.scalePics(inputStream,0.5,0.5);
 /**
     * 根据指定大小压缩图片
     * @param file  源图片
     * @param accuracy 指定图片缩放倍数
     * @return 压缩质量后的图片字节数组
     * scale 0~1 缩放倍数,1表示不缩放
     */
    public static byte[] scalePic(MultipartFile file, double accuracy) throws IOException {
        // 压缩图片并保存到临时文件中
        File tempFile = File.createTempFile("thumbnail", ".jpg");
        Thumbnails.of(file.getInputStream())
                .scale(0.5)
                .outputQuality(accuracy)
                .toFile(tempFile);
        // 读取临时文件的字节流设置到输出流中
        InputStream tempInputStream = new FileInputStream(tempFile);
        byte[] buffer = new byte[tempInputStream.available()];
        tempInputStream.read(buffer);
        tempInputStream.close();
        // 删除临时文件
        tempFile.delete();
        // 可以下载到本地看一看,是否真的缩小
        // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Code\\upload\\1.jpg"));
        // bos.write(buffer);
        // bos.close();
        return buffer;
    }


    public static byte[] scalePics(InputStream inputStream, double accuracy,double scale) throws IOException {
        // 压缩图片并保存到临时文件中
        File tempFile = File.createTempFile("thumbnail", ".jpg");
        Thumbnails.of(inputStream)
                .scale(scale)
                .outputQuality(accuracy)
                .toFile(tempFile);
        // 读取临时文件的字节流设置到输出流中
        InputStream tempInputStream = new FileInputStream(tempFile);
        byte[] buffer = new byte[tempInputStream.available()];
        tempInputStream.read(buffer);
        tempInputStream.close();
        // 删除临时文件
        tempFile.delete();
        // 下载到本地,
        // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Code\\upload\\1.jpg"));
        // bos.write(buffer);
        // bos.close();
        return buffer;
    }

你可能感兴趣的:(java,前端,服务器)