diff --git a/src/main/java/com/ycwl/basic/utils/ImageUtils.java b/src/main/java/com/ycwl/basic/utils/ImageUtils.java index fc62ba96..7a07d4e0 100644 --- a/src/main/java/com/ycwl/basic/utils/ImageUtils.java +++ b/src/main/java/com/ycwl/basic/utils/ImageUtils.java @@ -193,6 +193,52 @@ public class ImageUtils { } } + /** + * 旋转图片180度 + * + * @param sourceFile 源图片文件 + * @param targetFile 目标图片文件 + * @throws IOException 读取或写入文件失败 + */ + public static void rotateImage180(File sourceFile, File targetFile) throws IOException { + BufferedImage sourceImage = null; + BufferedImage rotatedImage = null; + try { + sourceImage = ImageIO.read(sourceFile); + if (sourceImage == null) { + throw new IOException("无法读取图片文件: " + sourceFile.getPath()); + } + + int width = sourceImage.getWidth(); + int height = sourceImage.getHeight(); + + // 创建旋转后的图片(宽高不变) + rotatedImage = new BufferedImage(width, height, sourceImage.getType()); + Graphics2D g2d = rotatedImage.createGraphics(); + + // 设置旋转变换 + AffineTransform transform = new AffineTransform(); + transform.translate(width / 2.0, height / 2.0); + transform.rotate(Math.PI); + transform.translate(-width / 2.0, -height / 2.0); + + g2d.setTransform(transform); + g2d.drawImage(sourceImage, 0, 0, null); + g2d.dispose(); + + // 保存旋转后的图片 + ImageIO.write(rotatedImage, "jpg", targetFile); + log.info("图片旋转180度成功,尺寸保持: {}x{}", width, height); + } finally { + if (sourceImage != null) { + sourceImage.flush(); + } + if (rotatedImage != null) { + rotatedImage.flush(); + } + } + } + /** * 智能裁切图片以填充目标尺寸,支持自动旋转以减少裁切损失 * @@ -330,10 +376,6 @@ public class ImageUtils { return source; } - if (degrees != 270) { - throw new IllegalArgumentException("仅支持270度旋转"); - } - int width = source.getWidth(); int height = source.getHeight();