package im.zhaojun.common.util;

import cn.hutool.core.codec.Base64Encoder;
import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ResizeImage {

    public static String resizeImageTo40K( byte[] bytes) {
        InputStream stream =new  ByteArrayInputStream(bytes);
        BufferedImage src=null;
        try {
            src= ImageIO.read(stream);
            if(null!=src) {
                BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
                String base64 = imageToBase64(output);
                if (base64.length() - base64.length() / 8 * 2 > 15000) {
                    output = Thumbnails.of(output).scale(1 / (base64.length() / 15000)).asBufferedImage();
                    base64 = imageToBase64(output);
                }
                return base64;
            }

        } catch (Exception e) {

            return imageToBase64(src);

        }
         return imageToBase64(src);
    }


    public static String imageToBase64(BufferedImage bufferedImage) {
        if(null==bufferedImage) return null;
        Base64Encoder encoder = new Base64Encoder();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {

            ImageIO.write(bufferedImage, "jpg", baos);

        } catch (IOException e) {

        }

        return new String(encoder.encode((baos.toByteArray())).replaceAll("\r\n",""));

    }


    private static InputStream BaseToInputStream(String base64string) {

        ByteArrayInputStream stream = null;

        try {

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64string);
            stream = new ByteArrayInputStream(bytes1);

        } catch (Exception e) {
            // TODO: handle exception
        }
        return stream;

    }


}
