package com.ruoyi.common.utils;

import com.ruoyi.common.utils.uuid.UUID;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageRotator {
    public static String rotate90DegreesCounterClockwise(String image, String path) {
        // 读取原始图片
        BufferedImage originalImage = null;
        try {
            originalImage = ImageIO.read(new File(image));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 创建一个旋转后的图片，宽度和高度交换
        BufferedImage rotatedImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), BufferedImage.TYPE_INT_ARGB);

        // 创建Graphics2D对象，用于绘制旋转后的图片
        Graphics2D g2d = rotatedImage.createGraphics();

        // 逆时针旋转90度
        AffineTransform at = new AffineTransform();
        at.translate(originalImage.getHeight(), 0);
        at.rotate(Math.toRadians(90));

        g2d.setTransform(at);
        g2d.drawImage(originalImage, 0, 0, null);
        g2d.dispose();

        String outPath = path + UUID.randomUUID() + ".png";
        // 保存旋转后的图片
        try {
            ImageIO.write(rotatedImage, "PNG", new File(outPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return outPath;
    }

    public static void main(String[] args) throws IOException {
        String path = "G:\\download\\";
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new File(path + "input.jpg"));

        // 创建一个旋转后的图片，宽度和高度交换
        BufferedImage rotatedImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), BufferedImage.TYPE_INT_ARGB);

        // 创建Graphics2D对象，用于绘制旋转后的图片
        Graphics2D g2d = rotatedImage.createGraphics();

        // 逆时针旋转90度
        AffineTransform at = new AffineTransform();
        at.translate(originalImage.getHeight(), 0);
        at.rotate(Math.toRadians(90));

        g2d.setTransform(at);
        g2d.drawImage(originalImage, 0, 0, null);
        g2d.dispose();

        // 保存旋转后的图片
        ImageIO.write(rotatedImage, "PNG", new File(path + "out.jpg"));

        System.out.println("图片旋转完成。");
    }


}