package com.yonge.toolset.base.util;

import com.yonge.toolset.base.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * Created by Eric.Shang on 2022/12/12.
 */
@Slf4j
public class ImUtil {

    public static String imageToBase64(String imgMessage, String suffix) {

        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            URL url = new URL(imgMessage);
            BufferedImage bufferedImage = Thumbnails.of(url).scale(0.1f).outputQuality(0.25f).asBufferedImage();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, suffix, outputStream);

            byte[] bytes = outputStream.toByteArray();
            outputStream.close();
            int length = bytes.length;
            //文件大小不能超过393216 Bytes
            if (length > 393216) {
                throw new BizException("文件过大请调整 像素 或 文件大小");
            }

            ImageIO.write(bufferedImage, suffix, baos);
        } catch (IOException e) {
            log.error("imageToBase64", e);
        }
        return new String(encoder.encode((baos.toByteArray())));
    }
}
