java 图片加水印(图片或者文本)

import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
 * @author jasonLu
 * @date 2017/5/11 12:30
 * @Description:图片添加水印 水印适用于 图片或文字
 */
public class WaterMaskImgUtils
{

    /**
     * 添加图片水印
     *
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param waterImg 水印图片路径,如:C://myPictrue//logo.png
     * @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     * @param degree 水印图片旋转角度
     */
    public static void pressImage(String targetImg, String waterImg,  int x, int y, float alpha, Integer degree,String suffix)
    {
         pressImage(targetImg,waterImg,null,x,y,alpha,null,suffix);
    }

    /**
     * 添加图片水印
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param waterImg 水印图片路径,如:C://myPictrue//logo.png
     * @param outImg 图片输出位置,如果为空,则覆盖原文件
     * @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     * @param degree 水印图片旋转角度
     */
    public static void pressImage(String targetImg, String waterImg, String outImg, int x, int y, float alpha, Integer degree,String suffix)
    {
        try
        {
            File file = new File(targetImg);
            //如果没有指定文件存放地址,则默认替换掉原图片
            File outFile;
            if(StringUtils.isEmpty(outImg))
            {
                outFile = file;
            }
            else
            {
                outFile = new File(outImg);
            }

            Image image = null;
            try
            {
                image = ImageIO.read(file);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);

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

            Image waterImage = ImageIO.read(new File(waterImg));    // 水印文件
            int width_1 = waterImage.getWidth(null);
            int height_1 = waterImage.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int widthDiff = width - width_1;
            int heightDiff = height - height_1;
            if (x < 0)
            {
                x = widthDiff / 2;
            }
            else if (x > widthDiff)
            {
                x = widthDiff;
            }
            if (y < 0)
            {
                y = heightDiff / 2;
            }
            else if (y > heightDiff)
            {
                y = heightDiff;
            }
            g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
            g.dispose();
            //注意这里的后缀不能带 .
            ImageIO.write(bufferedImage, suffix.substring(1), outFile);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 添加文字水印
     *
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param pressText 水印文字, 如:云账房
     * @param fontName 字体名称,    如:宋体
     * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小,单位为像素
     * @param color 字体颜色
     * @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     */
    public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, int y, float alpha,String suffix)
    {
        pressText(targetImg,pressText,null,fontName,fontStyle,fontSize,color,x,y,alpha,null,suffix);
    }

    /**
     * 添加文字水印
     * @Description 坐标(0,0)在图片的左上角,(负数,负数)在中心位置,(0,xxx)在左边,(x,0)在最上边,其他位置根据图片来确定
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param pressText 水印文字, 如:云账房
     * @param outImg 图片输出位置,如果为空,则覆盖原文件
     * @param fontName 字体名称,    如:宋体
     * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小,单位为像素
     * @param color 字体颜色
     * @param positionX 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
     * @param positionY 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     * @param degree 水印图片旋转角度
     */
    public static void pressText(String targetImg, String pressText, String outImg, String fontName, int fontStyle, int fontSize, Color color, int positionX, int positionY, float alpha, Integer degree,String suffix)
    {
        try
        {
            File file = new File(targetImg);
            // 如果没有指定文件存放地址,则默认替换掉原图片
            File outFile;
            if (StringUtils.isEmpty(outImg))
            {
                outFile = file;
            }
            else
            {
                outFile = new File(outImg);
            }
            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);
            Font font = new Font(fontName, fontStyle, fontSize);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);
            g.setFont(font);
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            if (null != degree)
            {
                // 设置水印旋转
                g.rotate(Math.toRadians(degree), (double) bufferedImage.getWidth() / 2, (double) bufferedImage.getHeight() / 2);
            }
            //获取文字所占的像素
            FontRenderContext context = g.getFontRenderContext();
            Rectangle2D stringBounds = font.getStringBounds(pressText,context);

            int textWidth = (int) stringBounds.getWidth() ;
            int textHeight = (int) stringBounds.getHeight();

            int widthDiff = width - textWidth;
            int heightDiff = height - textHeight;
            if (positionX < 0)
            {
                positionX = widthDiff / 2;
            }
            else if (positionX > widthDiff)
            {
                positionX = widthDiff;
            }
            if (positionY < 0)
            {
                positionY = heightDiff / 2;
            }
            else if (positionY > heightDiff)
            {
                positionY = heightDiff;
            }

            g.drawString(pressText, positionX, positionY + textHeight);
            g.dispose();
            ImageIO.write(bufferedImage, suffix, outFile);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    /**
     * 添加文字水印
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param pressText 水印文字, 如:云账房
     * @param fontName 字体名称,    如:宋体
     * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小,单位为像素
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     */
    public static void pressTextToRightBottom(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, Color color, float alpha,String suffix)
    {

        pressTextToRightBottom(targetImg,pressText,null,fontName,fontStyle,fontSize,color,alpha,null,suffix);
    }
    /**
     * 在图片的右下角添加水印
     *
     * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     * @param pressText 水印文字, 如:云账房
     * @param outImg 图片输出位置,如果为空,则覆盖原文件
     * @param fontName 体名称, 如:宋体
     * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小,单位为像素
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     * @param degree 水印图片旋转角度
     */
    public static void pressTextToRightBottom(String targetImg, String pressText, String outImg, String fontName, int fontStyle, int fontSize, Color color, float alpha, Integer degree,String suffix)
    {
        try
        {
            File file = new File(targetImg);
            File outFile;
            if (StringUtils.isEmpty(outImg))
            {
                outFile = file;
            }
            else
            {
                outFile = new File(outImg);
            }
            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);
            Font font = new Font(fontName, fontStyle, fontSize);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);
            g.setFont(font);
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            if (null != degree)
            {
                // 设置水印旋转
                g.rotate(Math.toRadians(degree), (double) bufferedImage.getWidth() / 2, (double) bufferedImage.getHeight() / 2);
            }

            //获取文字所占的像素
            FontRenderContext context = g.getFontRenderContext();
            Rectangle2D stringBounds = font.getStringBounds(pressText,context);

            int textWidth = (int) stringBounds.getWidth() ;
            int textHight = (int) stringBounds.getHeight();

            g.drawString(pressText, width - textWidth, height - textHight);
            g.dispose();
            ImageIO.write(bufferedImage, suffix.substring(1), outFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容