package com.hai.common.utils;


import com.hai.common.QRCodeGenerator;
import com.hai.config.CommonSysConst;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * 图片处理
 */
public class ImageUtils {

    public static void main(String[] args) throws Exception {
        String a = ImageToBase64ByOnline("https://oos.jyfwy.cn/common/test/test20210511.jpg");
        System.out.println(a);
    }

    public static String transferAlphaForHttp(InputStream inputStream){
        try {
            byte[] data = transferAlpha(null,inputStream,130);
            return byteArrayToBase64(data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String byteArrayToBase64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        System.out.println("值为：" + "data:image/jpg;base64," + png_base64);
        return "data:image/jpg;base64," + png_base64;
    }

    /**
     * 图片去白色的背景，并裁切
     *
     * @param image 图片
     * @param range 范围 1-255 越大 容错越高 去掉的背景越多
     * @return 图片
     * @throws Exception 异常
     */
    public static byte[] transferAlpha(Image image, InputStream in, int range) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            if (image == null && in != null) {
                image = ImageIO.read(in);
            }
            ImageIcon imageIcon = new ImageIcon(image);
            BufferedImage bufferedImage = new BufferedImage(imageIcon
                    .getIconWidth(), imageIcon.getIconHeight(),
                    BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon
                    .getImageObserver());
            int alpha = 0;
            int minX = bufferedImage.getWidth();
            int minY = bufferedImage.getHeight();
            int maxX = 0;
            int maxY = 0;

            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
                    .getHeight(); j1++) {
                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
                        .getWidth(); j2++) {
                    int rgb = bufferedImage.getRGB(j2, j1);

                    int R = (rgb & 0xff0000) >> 16;
                    int G = (rgb & 0xff00) >> 8;
                    int B = (rgb & 0xff);
                    if (((255 - R) < range) && ((255 - G) < range) && ((255 - B) < range)) { //去除白色背景；
                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
                    } else {
                        minX = minX <= j2 ? minX : j2;
                        minY = minY <= j1 ? minY : j1;
                        maxX = maxX >= j2 ? maxX : j2;
                        maxY = maxY >= j1 ? maxY : j1;
                    }
                    bufferedImage.setRGB(j2, j1, rgb);
                }
            }
            int width = maxX - minX;
            int height = maxY - minY;
            BufferedImage sub = bufferedImage.getSubimage(minX, minY, width, height);
            ImageIO.write(sub, "png", byteArrayOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        return byteArrayOutputStream.toByteArray();
    }

    public static byte[] transferAlphaAndRotate(Image image, InputStream in, int range, double angel) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            if (image == null && in != null) {
                image = ImageIO.read(in);
            }
            image = imageRotate(image,angel);
            ImageIcon imageIcon = new ImageIcon(image);
            BufferedImage bufferedImage = new BufferedImage(imageIcon
                    .getIconWidth(), imageIcon.getIconHeight(),
                    BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon
                    .getImageObserver());
            int alpha = 0;
            int minX = bufferedImage.getWidth();
            int minY = bufferedImage.getHeight();
            int maxX = 0;
            int maxY = 0;

            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
                    .getHeight(); j1++) {
                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
                        .getWidth(); j2++) {
                    int rgb = bufferedImage.getRGB(j2, j1);

                    int R = (rgb & 0xff0000) >> 16;
                    int G = (rgb & 0xff00) >> 8;
                    int B = (rgb & 0xff);
                    if (((255 - R) < range) && ((255 - G) < range) && ((255 - B) < range)) { //去除白色背景；
                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
                    } else {
                        minX = minX <= j2 ? minX : j2;
                        minY = minY <= j1 ? minY : j1;
                        maxX = maxX >= j2 ? maxX : j2;
                        maxY = maxY >= j1 ? maxY : j1;
                    }
                    bufferedImage.setRGB(j2, j1, rgb);
                }
            }
            int width = maxX - minX;
            int height = maxY - minY;
            BufferedImage sub = bufferedImage.getSubimage(minX, minY, width, height);
            ImageIO.write(sub, "png", byteArrayOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 图像旋转
     * @param src
     * @param angel
     * @return
     */
    public static BufferedImage imageRotate(Image src, double angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // calculate the new image size
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);

        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g2 = res.createGraphics();
        // transform
        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

        g2.drawImage(src, null, null);
        return res;
    }

    public static Rectangle CalcRotatedSize(Rectangle src, double angel) {
        // if angel is greater than 90 degree, we need to do some conversion
        if (angel >= 90) {
            if(angel / 90 % 2 == 1){
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        len_dalta_width=len_dalta_width>0?len_dalta_width:-len_dalta_width;

        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        len_dalta_height=len_dalta_height>0?len_dalta_height:-len_dalta_height;

        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        des_width=des_width>0?des_width:-des_width;
        des_height=des_height>0?des_height:-des_height;
        return new Rectangle(new Dimension(des_width, des_height));
    }


    /**
     * base64转inputStream
     * @param base64string
     * @return
     */
    public 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;
    }

    /**
     * 获取网络图片流
     *
     * @param url
     * @return
     */
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }


    public static String ImageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    public static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return  encoder.encode(Objects.requireNonNull(data));
    }

    public static String QrCodeImg(String imgPath , Integer id) throws Exception {
        // 生成二维码
        String qrCodeImg = "qrCode/" + id + ".png";
        String qrCodeUrl = CommonSysConst.getSysConfig().getFileUrl() + qrCodeImg;
        QRCodeGenerator.generateQRCodeImage(imgPath + id, 134, 134, qrCodeUrl);
        return qrCodeImg;
    }
}
