在 Spring Boot 3 中,要实现限制上传图片尺寸、格式以及对图片进行裁剪压缩处理,可以按照以下步骤进行。下面是一个完整的示例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
public class ImageUploadController {

    private static final String UPLOAD_DIR = "uploads";
    private static final String[] ALLOWED_TYPES = {"image/jpeg", "image/png", "image/gif"};
    private static final int MAX_WIDTH = 1920;
    private static final int MAX_HEIGHT = 1080;
    private static final int TARGET_WIDTH = 800;
    private static final int TARGET_HEIGHT = 600;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择要上传的图片", HttpStatus.BAD_REQUEST);
        }

        // 检查文件类型
        String contentType = file.getContentType();
        boolean isAllowed = false;
        for (String allowedType : ALLOWED_TYPES) {
            if (allowedType.equals(contentType)) {
                isAllowed = true;
                break;
            }
        }

        if (!isAllowed) {
            return new ResponseEntity<>("不支持的文件类型,仅支持 JPEG、PNG 和 GIF 格式", HttpStatus.BAD_REQUEST);
        }

        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            int width = image.getWidth();
            int height = image.getHeight();

            // 检查图片尺寸
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                return new ResponseEntity<>("图片尺寸过大,最大宽度为 " + MAX_WIDTH + ",最大高度为 " + MAX_HEIGHT, HttpStatus.BAD_REQUEST);
            }

            // 裁剪和压缩图片
            BufferedImage resizedImage = resizeImage(image, TARGET_WIDTH, TARGET_HEIGHT);

            // 创建上传目录(如果不存在)
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_DIR, fileName);

            // 保存处理后的图片
            String format = contentType.split("/")[1];
            ImageIO.write(resizedImage, format, filePath.toFile());

            return new ResponseEntity<>("图片上传并处理成功", HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("图片上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = resizedImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
        graphics2D.dispose();
        return resizedImage;
    }
}

代码说明

  1. 文件类型限制:
    • ALLOWED_TYPES 数组定义了允许上传的图片格式,在 uploadImage 方法中,通过 file.getContentType() 获取文件的 MIME 类型,并与 ALLOWED_TYPES 进行比较,若不匹配则返回错误信息。
  2. 图片尺寸限制:
    • MAX_WIDTH 和 MAX_HEIGHT 定义了允许上传的最大图片尺寸。在 uploadImage 方法中,使用 ImageIO.read 读取图片文件为 BufferedImage 对象,然后获取其宽度和高度,若超过最大尺寸则返回错误信息。
  3. 图片裁剪压缩处理:
    • TARGET_WIDTH 和 TARGET_HEIGHT 定义了处理后图片的目标尺寸。resizeImage 方法用于将原始图片按照目标尺寸进行裁剪和压缩,使用 Graphics2D 进行绘制,最后返回处理后的 BufferedImage 对象。
    • 在 uploadImage 方法中,调用 resizeImage 方法对图片进行处理,然后使用 ImageIO.write 将处理后的图片保存到指定目录。