上报图片直接进行裁切

This commit is contained in:
2025-07-17 17:59:14 +08:00
parent 78079b242a
commit 1ca7182979
5 changed files with 97 additions and 9 deletions

View File

@@ -3,7 +3,10 @@ package com.ycwl.basic.utils;
import cn.hutool.core.codec.Base64;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -21,6 +24,34 @@ public class ImageUtils {
}
return new Base64DecodedMultipartFile(b, baseStrs[0]);
}
public static MultipartFile cropImage(MultipartFile file, int x, int y, int w, int h) throws IOException {
BufferedImage image = ImageIO.read(file.getInputStream());
if (image.getWidth() > w) {
w = image.getWidth();
}
if (image.getHeight() > h) {
h = image.getHeight();
}
int targetX = x;
if (x < 0) {
targetX = 0;
} else if ((x + w) > image.getWidth()) {
targetX = image.getWidth() - w;
}
int targetY = y;
if (y < 0) {
targetY = 0;
} else if ((y + h) > image.getHeight()) {
targetY = image.getHeight() - h;
}
BufferedImage targetImage = image.getSubimage(targetX, targetY, w, h);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(targetImage, "jpg", baos);
baos.close();
return new Base64DecodedMultipartFile(baos.toByteArray(), "image/jpeg");
}
public static class Base64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;