图片调整

dev
zhaokai 2026-03-11 14:35:45 +08:00
parent bef972ca0d
commit a64fcc6f29
1 changed files with 23 additions and 15 deletions

View File

@ -12,32 +12,39 @@ import java.net.URL;
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;
public class ImageUtil {
public static PictureRenderData createWithThumbnailator(String imageUrl, int width, int height) {
try {
// 下载原图
URL url = new URL(imageUrl);
BufferedImage originalImage = ImageIO.read(url);
// 1. 读取EXIF判断是否需要旋转
int rotationAngle = getRotationAngleFromExif(url);
// 2. 根据判断结果决定是否旋转
BufferedImage processedImage;
if (rotationAngle != 0) {
// 需要旋转
processedImage = Thumbnails.of(originalImage)
// 使用Thumbnailator的增强配置
Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(originalImage)
.size(width, height)
.rotate(rotationAngle)
.asBufferedImage();
.outputQuality(1.0) // 最高质量
.imageType(BufferedImage.TYPE_INT_RGB) // 确保RGB类型
.useOriginalFormat() // 保持原始格式
.allowOverwrite(true); // 允许覆盖
// 设置缩放算法
if (width * height > 100000) { // 大图使用双三次插值
builder.scalingMode(ScalingMode.BICUBIC);
} else {
// 不需要旋转,只缩放
processedImage = Thumbnails.of(originalImage)
.size(width, height)
.asBufferedImage();
builder.scalingMode(ScalingMode.BILINEAR);
}
// 3. 转换为byte数组
BufferedImage processedImage;
if (rotationAngle != 0) {
processedImage = builder.rotate(rotationAngle).asBufferedImage();
} else {
processedImage = builder.asBufferedImage();
}
// 使用ImageIO写入设置更高的质量参数
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(processedImage, "jpg", baos);
@ -46,6 +53,7 @@ public class ImageUtil {
.create();
} catch (Exception e) {
e.printStackTrace();
return Pictures.ofUrl(imageUrl, PictureType.JPEG)
.size(width, height)
.create();