package cn.com.ty.lift.ud.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

/**
 * 給图片添加文字水印
 * 
 * @author liqiang
 *
 */
public class WaterMarkUtils {

    /**
     * 图片添加水印
     * 
     * @param srcImgFile
     *            需要添加水印的图片
     * @param outImgPath
     *            添加水印后图片输出路径
     * @param markContentColor
     *            水印文字的颜色
     * @param waterMarkContent
     *            水印的文字
     */
    public static void mark(String filePath, String outImgPath, String waterMarkContent) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(filePath);
            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.BOLD + Font.ITALIC, bufImg.getWidth()/16);
            g.setFont(font);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,0.3f));
            g.setColor(Color.black);
            g.setBackground(Color.white);
            g.rotate(Math.toRadians(-15),
                    (double) bufImg.getWidth() / 2, (double) bufImg
                    .getHeight() / 2);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
            int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) -200;
            int y = srcImgHeight - 150;
            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 void main(String[] args) {
        WaterMarkUtils.mark("C:\\Users\\Administrator\\Pictures\\1.jpg", "C:\\\\Users\\\\Administrator\\\\Pictures\\\\1.jpg", "图片来源天域电梯");
    }
}