java 给图片加上文字水印

 直接调用setImage方法,修改一下对应的参数 

package cn.jweb.core.utils.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.jweb.core.utils.ToolUtils;
import cn.jweb.modules.sys.entity.SysConfig;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * 添加水印util
 */
public class WatermarkUtil {
    /**
     * 读取本地图片
     *
     * @param path
     *            本地图片存放路径
     */
    public static Image readLocalPicture(String path) {
        if (null == path) {
            throw new RuntimeException("本地图片路径不能为空");
        }
        // 读取原图片信息 得到文件
        File srcImgFile = new File(path);
        try {
            // 将文件对象转化为图片对象
            return ImageIO.read(srcImgFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取网络图片
     *
     * @param path
     *            网络图片地址
     */
    public static Image readNetworkPicture(String path) {
        if (null == path) {
            throw new RuntimeException("网络图片路径不能为空");
        }
        try {
            // 创建一个URL对象,获取网络图片的地址信息
            URL url = new URL(path);
            // 将URL对象输入流转化为图片对象 (url.openStream()方法,获得一个输入流)
            BufferedImage bugImg = ImageIO.read(url.openStream());
            if (null == bugImg) {
                throw new RuntimeException("网络图片地址不正确");
            }
            return bugImg;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 水印处理
     *
     * @param fontSize
     *            文字字体大小
     * @param pos
     *            显示位置(0:居中;1:左上角;2:右上角;3:左下角;4:右下角)
     * @param image
     *            图片对象
     * @param type
     *            水印类型(1-文字水印 2-图片水印)
     * @param watermark
     *            水印内容(文字水印内容/图片水印的存放路径)
     */
    /**               方向度数,     颜色,  文字大小, 显示位置,父目录路径,文件名(不包括后缀名),文件后缀名, 图片,水印类型,水印名称*/
    public static String manageWatermark(int directDegree, Color fontColor, int fontSize, int pos,
            String destDir, String filePrefixName, String ext, Image image, Integer type, String watermark) {
        int imgWidth = image.getWidth(null);
        int imgHeight = image.getHeight(null);
        BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        // 加水印:
        // 创建画笔
        Graphics2D graphics = bufImg.createGraphics();
        // 绘制原始图片
        graphics.drawImage(image, 0, 0, imgWidth, imgHeight, null);
        // 方向
        AffineTransform at = new AffineTransform();
        // 校验水印的类型
        if (type == 1) {
            if (StringUtils.isEmpty(watermark)) {
                throw new RuntimeException("文字水印内容不能为空");
            }
            // 添加文字水印:
            // 根据图片的背景设置水印颜色
            // graphics.setColor(new Color(255, 255, 255, 128));
            graphics.setColor(fontColor);
            // 设置字体 画笔字体样式为微软雅黑,加粗,文字大小为45pt
            graphics.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
            int x = 0;
            int y = 0;
            int xTemp = 0;
            int yTemp = 0;
            // 设置水印的坐标(为原图片位置)
            // 显示位置(0:居中;1:左上角;2:右上角;3:左下角;4:右下角)
            if (pos == 0) {// 居中
                x = (imgWidth - getWatermarkLength(watermark, graphics)) / 2;
                y = imgHeight / 2;

                xTemp = imgWidth / 2;
                yTemp = imgHeight / 2;
            } else if (pos == 1) {// 左上角
                x = 10;
                y = fontSize + 10;
                System.out.println("-------------" + getWatermarkLength(watermark, graphics));
                xTemp = getWatermarkLength(watermark, graphics) - fontSize + 10;
                yTemp = getWatermarkLength(watermark, graphics) / 2 - fontSize + 10;
            } else if (pos == 2) {// 右上角
                x = (imgWidth - getWatermarkLength(watermark, graphics)) - 10;
                y = fontSize + 10;

                xTemp = imgWidth - 10;
                yTemp = fontSize + 10;
            } else if (pos == 3) {// 左下角
                x = 10;
                y = imgHeight - 10;

                xTemp = 10;
                yTemp = imgHeight - 10;
            } else if (pos == 4) {// 右下角
                x = (imgWidth - getWatermarkLength(watermark, graphics)) - 10;
                y = imgHeight - 10;

                xTemp = imgWidth - 10;
                yTemp = imgHeight - 10;
            }
            at.rotate(Math.toRadians(directDegree), xTemp, yTemp);
            graphics.setTransform(at);
            // 画出水印 第一个参数是水印内容,第二个参数是x轴坐标,第三个参数是y轴坐标
            graphics.drawString(watermark, x, y);
            graphics.dispose();
        } else {
            // 添加图片水印:
            if (StringUtils.isEmpty(watermark)) {
                throw new RuntimeException("图片水印存放路径不能为空");
            }
            Image srcWatermark = readLocalPicture(watermark);
            int watermarkWidth = srcWatermark.getWidth(null);
            int watermarkHeight = srcWatermark.getHeight(null);
            // 设置 alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
            int x = 0;
            int y = 0;
            // 显示位置(0:居中;1:左上角;2:右上角;3:左下角;4:右下角)
            if (pos == 0) {// 居中
                x = (imgWidth - watermarkWidth) / 2;
                y = (imgHeight - watermarkHeight) / 2;
            } else if (pos == 1) {// 左上角
                x = 10;
                y = 10;
            } else if (pos == 2) {// 右上角
                x = imgWidth - watermarkWidth - 10;
                y = 10;
            } else if (pos == 3) {// 左下角
                x = 10;
                y = imgHeight - watermarkHeight - 10;
            } else if (pos == 4) {// 右下角
                x = imgWidth - watermarkWidth - 10;
                y = imgHeight - watermarkHeight - 10;
            }
            int width = watermarkWidth;
            int height = watermarkHeight;
            at.rotate(Math.toRadians(directDegree), x, y);
            graphics.setTransform(at);
            graphics.drawImage(srcWatermark, x, y, width, height, null);
            graphics.dispose();
        }
        // 定义存储的地址
        String s = filePrefixName + "_" + type + "_" + ToolUtils.genRandomNum(5)
                + "." + ext;
        String tarImgPath = destDir + "/" + s;
//        return tarImgPath;
        // 输出图片
        try {
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "png", outImgStream);
            outImgStream.flush();
            outImgStream.close();
            return s;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加水印
     *
     * @param pictureType
     *            图片来源类型(1-本地图片 2-网络图片)
     * @param watermarkType
     *            水印类型(1-文字水印 2-图片水印)
     * @param path
     *            图片路径
     * @param watermark
     *            水印内容(文字水印内容/图片水印的存放路径)
     */
    /**                  方向度数,        颜色,     文字大小, 显示位置, 本地图片,      文字水印,    文件路径,     水印名称*/
    public static String addWatermark(int directDegree, Color fontColor, int fontSize, int pos,
            Integer pictureType, Integer watermarkType, String path, String watermark) {
        if (null == pictureType) {
            throw new RuntimeException("图片来源类型不能为空");
        }
        if (null == watermarkType) {
            throw new RuntimeException("水印类型不能为空");
        }
        // 获取文件后缀
        String ext = FileNameUtil.getSuffix(path); // 文件后缀名
        String filePrefixName = FileNameUtil.getPrefix(path); //文件名(不包括后缀名)
        String destDir = FileUtil.getParent(path, 1);//父目录路径
        // System.out.println(FileUtil.getAbsolutePath(path));
        // System.out.println(FileUtil.getParent(path, 1));
        // System.out.println("prefix==" + FileNameUtil.getPrefix(path));
        Image image;
        if (pictureType == 1) {
            // 读取本地图片
            image = readLocalPicture(path);
        } else {
            // 读取网络图片
            image = readNetworkPicture(path);
        }
        if (watermarkType == 1) {
            // 添加文字水印
                /**               方向度数,     颜色,  文字大小, 显示位置,父目录路径,文件名(不包括后缀名),文件后缀名, 图片,水印类型,水印名称*/
            return manageWatermark(directDegree, fontColor, fontSize, pos, destDir, filePrefixName, ext, image, 1, watermark);
        } else {
            // 添加图片水印
            return manageWatermark(directDegree, fontColor, fontSize, pos, destDir, filePrefixName, ext,
                    image, 2, watermark);
        }
    }

    /**
     * 获取水印文字的长度
     *
     * @param watermarkContent
     *            文字水印内容
     * @param graphics
     *            图像类
     */
    private static int getWatermarkLength(String watermarkContent, Graphics2D graphics) {
        return graphics.getFontMetrics(graphics.getFont()).charsWidth(watermarkContent.toCharArray(), 0,
                watermarkContent.length());
    }

    public static String  setImage(String localPath) {
        // 文字水印内容
        String textWatermark = "水印";// 
        // 图片水印路径
//        String pictureWatermark = "C:/Users/ZRH/Desktop/logo.png";
        // 显示位置(0:居中;1:左上角;2:右上角;3:左下角;4:右下角)
        int pos = 1;// 显示位置
        int fontSize = 30;// 文字大小
        int directDegree = 45;// 方向度数
        // 颜色
        Color fontColor =  new Color(255,255,255,128);
        //图片位置
        String localPath= "D:/image.jpg";
       
        /**                  方向度数,        颜色,     文字大小, 显示位置, 本地图片,      文字水印,    文件路径,     水印名称,*/
        return addWatermark(directDegree, fontColor, fontSize, pos, 1, 1, localPath, textWatermark);
      
        // 本地图片 添加图片水印
        // addWatermark(fontColor, fontSize, 0, 1, 2, localPath,
        // pictureWatermark);

    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值