package com.inkasso.factoring.common.util;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.core.io.ClassPathResource;

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

/**
 * @author liutao
 * 图片添加水印
 */
public class WaterMarkUtils {
    /**
     * @param is 源图片文件
     * @param tarImgPath 保存的图片路径
     * @param waterMarkContent 水印内容
     * @param markContentColor 水印颜色
     * @param font 水印字体
     */
    public static void addWaterMark(InputStream is, String tarImgPath, String waterMarkContent,Color markContentColor,Font font) {

        try {
            Image srcImg = ImageIO.read(is);//文件转化为图片
            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(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font);              //设置字体

            //设置水印的坐标
            int x = srcImgWidth - 2*getWatermarkLength(waterMarkContent, g);
            int y = srcImgHeight - 50;

            g.drawString(waterMarkContent, x, y);  //画出水印
            g.dispose();
            //输出图片到本地
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            System.out.println("添加水印完成");
            outImgStream.flush();
            outImgStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
    public static void main(String[] args) throws IOException {
        Font font = new Font("黑体", Font.BOLD, 35);                     //水印字体
        String srcImgPath="static/lemonsTeaSign/1.jpg"; //源图片地址
        String tarImgPath="D:1/1.jpg"; //待存储的地址
        File file = new File(tarImgPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String waterMarkContent= DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);  //水印内容
        Color color=new Color(0,0,0,250);                               //水印图片色彩以及透明度
        //读取本地的原图片信息
        ClassPathResource classPathResource = new ClassPathResource(srcImgPath);
        File srcImgFile = classPathResource.getFile();
        //addWaterMark(srcImgFile, tarImgPath,  waterMarkContent,color,font);
    }
}
