开发者

基于SpringBoot实现图片上传并生成缩略图功能

目录
  • 1. 依赖配置
  • 2. 核心代码实现
  • 3. 计算缩略图尺寸方法
  • 4. 工具方法示例
  • 5. 注意事项
  • 6. 总结

在实际开发中,上传图片并生成缩略图是一项常见需求,例如在电商平台、社交应用等场景中,缩略图可以有效提高页面加载速度,优化用户体验。本文将介绍如何编程客栈在 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);
         ABOlwcWk   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) {python
            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. 工具方法示例

用于提取文件后缀名:

5. 注意事项

  1. 操作系统临时目录:根据不同操作系统,创建不同的临时文件夹路径。
  2. 文件清理:上传完成后及时删除临时文件,避免占用过多磁盘空间。
  3. 缩略图格式支持:目前支持 PNG、JPG、JPEG、GIF 格式。
  4. 上传逻辑uploadFile 方法需根据具体的存储服务(例如 MinIO、OSS、七牛云等)自定义实现。

6. 总结

通过以上步骤,我们成功实现了图片上传并生成缩略图的功能。此功能不仅能有效减少图片加载时间,还能节省存储空间,提升系统性能。

到此这篇关于基于SpringBoot实现图片上传并生成缩略图功能的文章就介绍到这了,更多相关SpringBoot图片上传并生成缩略图内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜