欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Spring Boot 实现图片上传并生成缩略图功能

Spring Boot 实现图片上传并生成缩略图功能

2025/2/27 4:02:47 来源:https://blog.csdn.net/weixin_62490394/article/details/145847185  浏览:    关键词:Spring Boot 实现图片上传并生成缩略图功能

在实际开发中,上传图片并生成缩略图是一项常见需求,例如在电商平台、社交应用等场景中,缩略图可以有效提高页面加载速度,优化用户体验。本文将介绍如何在 Spring Boot 项目中实现上传图片并生成缩略图的功能。

📦 1. 依赖配置

pom.xml 文件中添加以下依赖:

<!-- Spring Boot Web -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- 文件上传 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId>
</dependency><!-- 图片处理依赖 -->
<dependency><groupId>com.twelvemonkeys.imageio</groupId><artifactId>imageio-core</artifactId><version>3.8.1</version>
</dependency><!-- Apache Commons IO -->
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.8.0</version>
</dependency>
📂 2. 核心代码实现

以下方法将实现图片上传并生成缩略图的功能:

import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;public String uploadPictureThumbnail(String bucketName, MultipartFile multipartFile, Long assocId, String originalStorageName, Integer scale, Integer width, Integer height) {String directoryPath = "";if (OsUtils.isLinux()) {directoryPath = "/tempdir";} else if (OsUtils.isWindows()) {directoryPath = "C:/tempdir";}File directory = new File(directoryPath);if (!directory.exists()) {directory.mkdir();}String originalName = multipartFile.getOriginalFilename();String suffixName = getSuffixName(originalName, ".", 0);String suffix = getSuffixName(originalName, ".", 1);String storageName = UUID.randomUUID().toString() + suffixName;String storageFileName = null;List<String> thumbnailSuffixName = Arrays.asList(".png", ".jpg", ".jpeg", ".gif");if (thumbnailSuffixName.contains(suffixName.toLowerCase())) {try {// 保存原始图片String originalImagePath = directoryPath + "/" + storageName;Path filePath = Paths.get(originalImagePath);Files.write(filePath, multipartFile.getBytes());// 读取原始图片并生成缩略图BufferedImage originalImage = ImageIO.read(new File(originalImagePath));int originalWidth = originalImage.getWidth();int originalHeight = originalImage.getHeight();// 计算缩略图尺寸int[] data = computeSize(originalWidth, originalHeight, scale, width, height);int thumbnailWidth = data[0];int thumbnailHeight = data[1];Image scaledImage = originalImage.getScaledInstance(thumbnailWidth, thumbnailHeight, Image.SCALE_SMOOTH);BufferedImage thumbnailImage = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = thumbnailImage.createGraphics();g2d.drawImage(scaledImage, 0, 0, null);g2d.dispose();// 保存缩略图String thumbnailPath = directoryPath + "/" + UUID.randomUUID().toString() + suffixName;File thumbnailFile = new File(thumbnailPath);ImageIO.write(thumbnailImage, suffix.replace(".", ""), thumbnailFile);// 上传缩略图(这里用自定义 uploadFile 方法上传到对象存储)try (FileInputStream in = new FileInputStream(thumbnailFile)) {String name = getSuffixName(originalStorageName, "/", 1);storageFileName = uploadFile(bucketName, in, multipartFile.getContentType(), assocId, thumbnailFile.length(), name, "thumbnail");}// 清理临时文件new File(originalImagePath).delete();thumbnailFile.delete();} catch (IOException e) {e.printStackTrace();}}return storageFileName;
}
🔧 3. 计算缩略图尺寸方法

根据原始尺寸、比例、指定宽高生成合适的缩略图尺寸:

private int[] computeSize(int originalWidth, int originalHeight, Integer scale, Integer width, Integer height) {if (scale != null && scale > 0) {return new int[]{originalWidth * scale / 100, originalHeight * scale / 100};} else if (width != null && height != null) {return new int[]{width, height};} else {// 默认缩小为原始尺寸的 50%return new int[]{originalWidth / 2, originalHeight / 2};}
}
📝 4. 工具方法示例

用于提取文件后缀名:

private String getSuffixName(String fileName, String delimiter, int index) {String[] parts = fileName.split(delimiter);if (index < parts.length) {return delimiter + parts[parts.length - 1];}return "";
}
⚠️ 5. 注意事项
  1. 操作系统临时目录:根据不同操作系统,创建不同的临时文件夹路径。

  2. 文件清理:上传完成后及时删除临时文件,避免占用过多磁盘空间。

  3. 缩略图格式支持:目前支持 PNG、JPG、JPEG、GIF 格式。

  4. 上传逻辑uploadFile 方法需根据具体的存储服务(例如 MinIO、OSS、七牛云等)自定义实现。

🎯 6. 总结

通过以上步骤,我们成功实现了图片上传并生成缩略图的功能。此功能不仅能有效减少图片加载时间,还能节省存储空间,提升系统性能。如果你在实现过程中遇到问题,欢迎在评论区留言讨论!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词