package org.dromara.common.utils;

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

public class ImageUtils {
    
    /**
     * 处理图片水印并缩放为800x800
     * @param inputPath 输入图片路径
     * @param outputPath 输出图片路径
     * @param watermarkText 水印文字
     * @throws IOException
     */
    public static void processImageWithWatermark(String inputPath, String outputPath, String watermarkText) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new File(inputPath));
        
        // 创建新图片，尺寸为800x800
        BufferedImage newImage = new BufferedImage(800, 800, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = newImage.createGraphics();
        
        // 设置背景为白色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, 800, 800);
        
        // 计算缩放比例并绘制缩放后的图片
        double scale = Math.min(800.0 / originalImage.getWidth(), 800.0 / originalImage.getHeight());
        int width = (int) (originalImage.getWidth() * scale);
        int height = (int) (originalImage.getHeight() * scale);
        int x = (800 - width) / 2;
        int y = (800 - height) / 2;
        g2d.drawImage(originalImage, x, y, width, height, null);
        
        // 添加水印
        if (watermarkText != null && !watermarkText.isEmpty()) {
            g2d.setColor(new Color(255, 255, 255, 128));
            g2d.setFont(new Font("Arial", Font.BOLD, 20));
            
            // 计算水印位置（图片底部）
            FontMetrics fm = g2d.getFontMetrics();
            int textWidth = fm.stringWidth(watermarkText);
            int textY = 800 - 30; // 距离底部30像素
            int textX = (800 - textWidth) / 2;
            
            // 绘制水印背景（半透明黑色）
            g2d.setColor(new Color(0, 0, 0, 128));
            g2d.fillRect(textX - 10, textY - fm.getHeight() + 5, 
                         textWidth + 20, fm.getHeight() + 5);
            
            // 绘制水印文字
            g2d.setColor(Color.WHITE);
            g2d.drawString(watermarkText, textX, textY);
        }
        
        g2d.dispose();
        
        // 保存图片
        ImageIO.write(newImage, "jpg", new File(outputPath));
    }
}