使用Java实现图片大小压缩

使用Java实现图片大小压缩

在现代应用程序中,图片的大小对于存储和传输至关重要。较大的图片文件可能会影响网站的加载速度和用户体验。通过压缩图片大小,可以显著减少文件尺寸,提高性能。本文将介绍如何使用Java进行图片压缩,具体实现包括从输入流读取图片、压缩图片并通过输出流返回压缩后的图片数据。

1. 环境依赖

在开始之前,需要添加Thumbnailator库作为图片压缩的依赖。可以在Maven项目的pom.xml中添加以下依赖:

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.20</version>
</dependency>

2. 压缩图片的方法

我们将创建一个工具类FileUtil,其中包含压缩图片的方法compressImage。该方法接收输入图片流、输出图片流和压缩质量参数,并使用Thumbnailator库进行图片压缩。

import net.coobird.thumbnailator.Thumbnails;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
    
    /**
     * 压缩图片文件大小
     *
     * @param inputStream  输入图片流
     * @param outputStream 输出图片流
     * @param quality      压缩质量 (0.0 到 1.0,1.0表示最高质量)
     * @throws IOException
     */
    public static void compressImage(InputStream inputStream, OutputStream outputStream, float quality) throws IOException {
        // 使用Thumbnailator进行压缩
        Thumbnails.of(inputStream)
                .scale(1.0) // 保持原始尺寸
                .outputQuality(quality)
                .toOutputStream(outputStream);
    }
}

3. 压缩图片的RESTful接口

接下来,我们创建一个Spring Boot控制器ImageController,其中包含一个RESTful接口compressImage,用于压缩图片并以流的形式返回压缩后的图片。

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

@RestController
@RequestMapping("/image")
public class ImageController {
    
    private static final float PER_QUALITY = 0.8f; // 设置默认的压缩质量

    @RequestMapping(value = "/compress/{fileName}", method = RequestMethod.GET)
    public ResponseEntity<StreamingResponseBody> compressImage(@PathVariable("fileName") String filename) {
        // 获取要下载的文件
        File file = new File("C:\\Users\\shy\\Desktop\\" + filename);
        StreamingResponseBody stream = outputStream -> {
            try (InputStream inputStream = Files.newInputStream(file.toPath())) {
                // 调用图片压缩方法
                FileUtil.compressImage(inputStream, outputStream, PER_QUALITY);
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + "compress_" + file.getName())
                .contentType(MediaType.IMAGE_JPEG)
                .body(stream);
    }
}

4. 测试接口

在浏览器或Postman中访问以下URL可以测试图片压缩接口:

http://localhost:8080/image/compress/your_image_file.jpg

其中your_image_file.jpg是你希望压缩的图片文件名。压缩后的图片将会以compress_your_image_file.jpg的形式下载。

压缩前的文件:
在这里插入图片描述
压缩后的文件:
在这里插入图片描述
我们可以看到,文件已经成功被压缩到了409KB,测试成功!!!

5. 总结

通过上述步骤,我们实现了一个简单的图片压缩工具,并通过Spring Boot提供了一个RESTful接口来压缩并下载图片。该方法能够有效减少图片文件的大小,从而提高应用程序的性能和用户体验。

希望这篇博客能对你在Java开发中处理图片压缩有所帮助。如果有任何问题或建议,欢迎在评论区留言讨论。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shy好好学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值