package com.ruoyi.framework.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageCompressor {


    // 压缩Base64图片
    public static String compressBase64Image(String base64Image, float quality, int maxWidth, int maxHeight) {
        try {
            // 去除Base64前缀
            String base64Data = base64Image.replaceAll("data:image/.*?;base64,", "");

            // 解码Base64为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 读取图片
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            // 计算压缩后的尺寸
            int[] newDimensions = calculateDimensions(originalImage.getWidth(), originalImage.getHeight(), maxWidth, maxHeight);
            int newWidth = newDimensions[0];
            int newHeight = newDimensions[1];

            // 创建压缩后的图片
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g.dispose();

            // 压缩图片质量
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(resizedImage, "jpg", outputStream);

            // 编码为Base64并添加前缀
            String compressedBase64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + compressedBase64;

        } catch (IOException e) {
            // 处理异常，无法压缩时返回原图
            return base64Image;
        }
    }

    // 计算压缩后的尺寸，保持比例
    private static int[] calculateDimensions(int originalWidth, int originalHeight, int maxWidth, int maxHeight) {
        if (originalWidth <= maxWidth && originalHeight <= maxHeight) {
            return new int[]{originalWidth, originalHeight};
        }

        double widthRatio = (double) maxWidth / originalWidth;
        double heightRatio = (double) maxHeight / originalHeight;
        double ratio = Math.min(widthRatio, heightRatio);

        return new int[]{
                (int) (originalWidth * ratio),
                (int) (originalHeight * ratio)
        };
    }
}
