package com.yunniu.farming.util;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;


public class ImageUtil {
    public static String saveFile(String path, MultipartFile pic) throws IllegalStateException, IOException {
        String originalFileName = pic.getOriginalFilename();
        // 新的图片名称
        String newFileName = UUIDUtils.getUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 新的图片
        File newFile = new File(path + newFileName);
        // 文件夹路径不存在
        if (!newFile.exists() && !newFile.isDirectory()) {
            newFile.mkdirs();
        }
        // 将内存中的数据写入磁盘
        pic.transferTo(newFile);
        return newFileName;
    }


    public static void main(String[] args) {
        String s = imageToBase64("C:\\upload\\123.png");
        System.out.println(s);
    }


    /**
     * @param LoadPath
     * @return
     */
    public static String imageToBase64(String LoadPath) {
        byte[] ImgContainer = null;    //数据集缓存器
        FileInputStream fileInputStream = null; //文件输入流
        try {
            System.out.println(LoadPath);
            fileInputStream = new FileInputStream(LoadPath);    //到指定路径寻找文件
            ImgContainer = new byte[fileInputStream.available()];          //设置图片字节数据缓冲区大小
            fileInputStream.read(ImgContainer);           //将数据流中的图片数据读进缓冲区
            String Base64ImgData = new String(org.apache.tomcat.util.codec.binary.Base64.encodeBase64(ImgContainer));  //将图片编码转换成Base64格式的数据集
            fileInputStream.close();      //关闭数据流
            File file = new File(LoadPath);
            file.delete();
            return "data:image/png;base64," + Base64ImgData;  //将缓冲区数据转换成字符数据返回
        } catch (FileNotFoundException e) {
            return "找不到指定文件!";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    // base64字符串转化成图片
    public static boolean GenerateImage(String imgStr, String savepath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        File newFile = new File(savepath.substring(0, savepath.lastIndexOf("/")));
        // 文件夹路径不存在
        if (!newFile.exists() && !newFile.isDirectory()) {
            newFile.mkdirs();
        }
//        BASE64Decoder decoder = new BASE64Decoder();
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            // Base64解码
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(savepath);
            out.write(b);
            out.flush();
            out.close();
            // 压缩图片
            //Thumbnails.of(savepath).scale(0.50f).toFile(savepath);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 为图片添加图片水印
     *
     * @param watermarkUrl 原图
     * @param source       水印图片
     * @param output       制作完成的图片
     * @return
     * @throws IOException
     */
    public static String markImgMark(String watermarkUrl, String source, String output) throws IOException {
        String result = "添加图片水印出错";
        File file = new File(source);
        Image img = ImageIO.read(file);
        int width = img.getWidth(null);//水印宽度
        int height = img.getHeight(null);//水印高
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ImageIcon imgIcon = new ImageIcon(watermarkUrl);
        Image con = imgIcon.getImage();
        float clarity = 0.6f;//透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));
        g.drawImage(con, 10, 10, null);//水印的位置
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        g.dispose();
        File sf = new File(output);
        ImageIO.write(bi, "jpg", sf); // 保存图片
        System.out.println("添加图片水印成功");
        return result;
    }

    /**
     * 设置文字水印
     *
     * @param sourceImg 源图片路径
     * @param targetImg 保存的图片路径
     * @param watermark 水印内容
     * @param color     水印颜色
     * @param font      水印字体
     * @throws IOException
     */
    public static void addWatermark(String sourceImg, String targetImg, String watermark, Color color, Font font) throws IOException {
        File srcImgFile = new File(sourceImg);
        Image srcImg = ImageIO.read(srcImgFile);
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        g.setColor(color);
        g.setFont(font);
        //设置水印的坐标
        int x = srcImgWidth - (g.getFontMetrics(g.getFont()).charsWidth(watermark.toCharArray(), 0, watermark.length()) + 20);
        int y = srcImgHeight - 25;
        g.drawString(watermark, x, y);  //加水印
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(targetImg);
        ImageIO.write(bufImg, "jpg", outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();
    }

    public static void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //Font font = new Font("Courier New", Font.PLAIN, 12);
            Font font = new Font("宋体", Font.PLAIN, 144);
            g.setColor(markContentColor); // 根据图片的背景设置水印颜色

            g.setFont(font);
//            int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
//            int y = srcImgHeight - 3;
            int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g)) / 2;
            int y = srcImgHeight / 2;
            g.drawString(waterMarkContent, x, y);
            g.dispose();
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent 水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    //定义图片水印字体类型
    public static final String FONT_NAME = "SimHei";

    //定义图片水印字体加粗、变细、倾斜等样式
    public static final int FONT_STYLE = Font.BOLD;

    //设置字体大小
    public static final int FONT_SIZE = 60;

    //设置文字透明程度
    public static float ALPHA = 0.3F;

    /**
     * 给图片添加多个文字水印、可设置水印文字旋转角度
     * source 需要添加水印的图片路径
     * outPut 添加水印后图片输出路径
     * imageName 图片名称
     * imageType 图片类型
     * color 水印文字的颜色
     * word 水印文字
     * degree 水印文字旋转角度，为null表示不旋转
     */
    public static Boolean markImageByMoreText(String sourcePath, String imageName, Color color, String word, Integer degree) {
        try {
            //读取原图片信息
            File file = new File(sourcePath);

            if (!file.isFile()) {
                return false;
            }

            //获取源图像的宽度、高度
            Image image = ImageIO.read(file);
            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            //创建绘图工具对象
            Graphics2D graphics2D = bufferedImage.createGraphics();
            //其中的0代表和原图位置一样
            graphics2D.drawImage(image, 0, 0, width, height, null);

            //设置水印文字（设置水印字体样式、粗细、大小）
            graphics2D.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));

            //设置水印颜色
            graphics2D.setColor(color);

            //设置水印透明度
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));

            //设置水印旋转
            if (null != degree) {
                graphics2D.rotate(Math.toRadians(degree), (double) bufferedImage.getWidth() / 2, (double) bufferedImage.getHeight() / 2);
            }

            int x = width / 3;
            int y = FONT_SIZE;
            int space = height / FONT_SIZE;
            for (int i = 0; i < space; i++) {
                //如果最后一个坐标的y轴比height高，直接退出
                if ((y + FONT_SIZE) > height) {
                    break;
                }
                //进行绘制
                graphics2D.drawString(word, x, y);
                y += (2 * FONT_SIZE);
            }

            graphics2D.dispose();

            //输出图片
            File sf = new File(FileUtil.Path + "/", imageName);
            // 保存图片
            ImageIO.write(bufferedImage, "jpg", sf);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
