JAVA 添加图片水印

参考资料:https://zhuanlan.zhihu.com/p/75110629

在参考基础上增加了水印位置功能:左上、右上、左下、右下、中间

public static void addWaterMark(File srcImgFile, SysWaterMark waterMark) {
    String text = waterMark.getWaterMark();
        Integer position = waterMark.getPosition();
        Integer num = waterMark.getNum();
        if (StringUtils.isEmpty(text)) {
            text = "数据来源:牛掰克拉斯";
        }
        if (position == null) {
            position = 5;
        }
        try {
            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 对象
            Graphics2D g = bufImg.createGraphics();
            int height = bufImg.getHeight();
            int width = bufImg.getWidth();
            //设置绘图区域
            g.drawImage(srcImg, 0, 0, width, height, null);
            //设置字体
            Integer size = height / 10;
        Font font = new Font("宋体", Font.PLAIN, size);
        // 根据图片的背景设置水印颜色
        g.setColor(Color.gray);
        g.setFont(font);
        //获取文字长度
        int len = g.getFontMetrics(
                g.getFont()).charsWidth(text.toCharArray(),
                0,
                text.length());
        int x = srcImgWidth - len - 10;
        int y = srcImgHeight - size;
        if (num == null || num <= 1) {
            if (position == 1) {
                g.drawString(text, 0, size);
            }
            if (position == 2) {
                g.drawString(text, x, size);
            }
            if (position == 3) {
                g.drawString(text, x/2 , y/2);
            }
            if (position == 4) {
                g.drawString(text, 0,  y+size-10);
            }
            if (position == 5) {
                g.drawString(text, x, y+size-10);
            }
        } else {
            for (int i = 0; i < num; i++) {
                g.drawString(text, x, y - (height / 100) * i);
            }
        }
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(srcImgFile);
        ImageIO.write(bufImg, "png", outImgStream);
        outImgStream.flush();
        outImgStream.close();
        System.out.println("OKOK");
        System.out.println(JSONObject.toJSONString(waterMark));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/wdz985721191/article/details/118669200