package com.xinelu.common.utils.file;

import com.xinelu.common.config.SystemBusinessConfig;
import com.xinelu.common.constant.Constants;

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

/**
 * 图片裁剪
 *
 * @author: zh
 * @create: 2024-08-22
 **/
public class ImageResize {

    public static void scaledDown(String pictureName) {
        try {
            pictureName = pictureName.replaceAll(Constants.RESOURCE_PREFIX, SystemBusinessConfig.getProfile());
            File inputFile = new File(pictureName);
            BufferedImage inputImage = ImageIO.read(inputFile);
            if (inputImage.getWidth() < 1080) {
                return;
            }
            // 新的宽度
            int newWidth = 1080;
            int newHeight = (int) ((double) inputImage.getHeight() / inputImage.getWidth() * newWidth);
            // 计算新的高度
            BufferedImage outputImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outputImage.createGraphics();
            g2d.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();
            File outputFile = new File(pictureName);
            ImageIO.write(outputImage, "jpg", outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}