package com.pj.project4sp.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.StaticLog;
import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;

public class ImageUtils {

    private static final Integer KB = 1024;


    // 将Base64字符串解码为BufferedImage
    public static BufferedImage base64ToBufferedImage(String base64Image) throws IOException {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bais);
    }

    // 将BufferedImage转回Base64字符串
    public static String bufferedImageToBase64(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    /**
     * 图片压缩指定长宽处理
     *
     * @param base64Image
     * @return
     */
    // 压缩图片至指定大小
    public static String compressPic(String base64Image) {
        BufferedImage originalImage = null;
        try {
            originalImage = base64ToBufferedImage(base64Image);
        } catch (IOException e) {
            return base64Image;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        double quality = 1.0; // 初始质量
        long imageSizeBytes = Long.MAX_VALUE;

        // 使用缩放和调整图片质量的循环，直到图片小于指定大小
        while (imageSizeBytes / (1024 * 1024) >= 4) {

            baos.reset(); // 重置输出流
            try {
                Thumbnails.of(originalImage)
                        .scale(1.0) // 保持原始尺寸，可以根据需要调整
                        .outputQuality(quality) // 调整图片质量
                        .outputFormat("jpg") // 输出格式
                        .toOutputStream(baos);
            } catch (IOException e) {
                return base64Image;
            }
            imageSizeBytes = baos.size();
            // 递减图片质量
            quality -= 0.05;
            if (quality < 0.05) { // 避免质量过低
                return base64Image;
            }
        }
        // 压缩成功，将图片转为Base64
        byte[] compressedImageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(compressedImageBytes);
    }

    public static String resizeImageBase64(String base64Input) throws IOException {
        int targetWidth = 480;
        int targetHeight = 720;
        byte[] imageBytes = Base64.getDecoder().decode(base64Input);

        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage originalImage = ImageIO.read(bais);
            BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
            g2d.dispose();

            ImageIO.write(resizedImage, "jpg", baos);
            byte[] newImageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(newImageBytes);
        }
    }
    public static  byte[]  resizeByteImageBase64(String base64Input) throws IOException {
        int targetWidth = 720;
        int targetHeight = 1080;
        byte[] imageBytes = Base64.getDecoder().decode(base64Input);

        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage originalImage = ImageIO.read(bais);
            BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
            g2d.dispose();

            ImageIO.write(resizedImage, "jpg", baos);
            return baos.toByteArray();
        }
    }

    public static String encodeFileToBase64Binary(String fileName) throws IOException {
        // 读取文件到字节数组
        byte[] fileContent = Files.readAllBytes(new File(fileName).toPath());
        // 使用Base64编码字节数组
        return Base64.getEncoder().encodeToString(fileContent);

    }

}
