Java实现文字水印铺满整张图

博客介绍了斜水印和正水印效果,若现有效果不满足需求可自行调整,还给出了实现这些效果的工具类代码和测试类代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 实现效果

      斜水印效果:

                                       

     正水印效果:

                                        

   如果这些效果还不能满足的话,自己可以稍微做一下调整就可以了。

  • 工具类代码

package com.zz;

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 java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

/**
 * 
 * @Title ImageWatermarkUtil
 * @Description
 * @author Zheng.Zeng
 * @date 2018年8月29日 下午4:47:38
 */
public class ImageWatermarkUtil {
    // 水印透明度
    private static float alpha = 0.5f;
    // 水印文字大小
    public static final int FONT_SIZE = 28;
    // 水印文字字体
    private static Font font = new Font ("微软雅黑", Font.BOLD, FONT_SIZE);
    // 水印文字颜色
    private static Color color = Color.white;
    // 水印之间的间隔
    private static final int XMOVE = 80;
    // 水印之间的间隔
    private static final int YMOVE = 80;

    /**
     * 获取文本长度。汉字为1:1,英文和数字为2:1
     */
    private static int getTextLength (String text) {
        int length = text.length ();
        for (int i = 0; i < text.length (); i++) {
            String s = String.valueOf (text.charAt (i));
            if (s.getBytes ().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }

    /**
     * 给图片添加水印文字
     * 
     * @param logoText 水印文字
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     */
    public static void ImageByText (String logoText, String srcImgPath, String targerPath) {
        ImageByText (logoText, srcImgPath, targerPath, null);
    }

    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     * 
     * @param logoText
     * @param srcImgPath
     * @param targerPath
     * @param degree
     */
    public static void ImageByText (String logoText, String srcImgPath, String targerPath, Integer degree) {

        InputStream is = null;
        OutputStream os = null;
        try {
            // 源图片
            Image srcImg = ImageIO.read (new File (srcImgPath));
            int width = srcImg.getWidth (null);// 原图宽度
            int height = srcImg.getHeight (null);// 原图高度
            BufferedImage buffImg = new BufferedImage (srcImg.getWidth (null), srcImg.getHeight (null),
                                                       BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics ();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint (RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage (srcImg.getScaledInstance (srcImg.getWidth (null), srcImg.getHeight (null), Image.SCALE_SMOOTH),
                         0, 0, null);
            // 设置水印旋转
            if (null != degree) {
                g.rotate (Math.toRadians (degree), (double) buffImg.getWidth () / 2, (double) buffImg.getHeight () / 2);
            }
            // 设置水印文字颜色
            g.setColor (color);
            // 设置水印文字Font
            g.setFont (font);
            // 设置水印文字透明度
            g.setComposite (AlphaComposite.getInstance (AlphaComposite.SRC_ATOP, alpha));

            int x = -width / 2;
            int y = -height / 2;
            int markWidth = FONT_SIZE * getTextLength (logoText);// 字体长度
            int markHeight = FONT_SIZE;// 字体高度

            // 循环添加水印
            while (x < width * 1.5) {
                y = -height / 2;
                while (y < height * 1.5) {
                    g.drawString (logoText, x, y);

                    y += markHeight + YMOVE;
                }
                x += markWidth + XMOVE;
            }
            // 释放资源
            g.dispose ();
            // 生成图片
            os = new FileOutputStream (targerPath);
            ImageIO.write (buffImg, "JPG", os);
            System.out.println ("添加水印文字成功!");
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            try {
                if (null != is)
                    is.close ();
            } catch (Exception e) {
                e.printStackTrace ();
            }
            try {
                if (null != os)
                    os.close ();
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }
}
  • 测试类代码

package com.zz;

public class test {
    public static void main (String[] args) {
        String srcImgPath = "C:\\Users\\Administrator\\Desktop\\12.jpg";
        // 水印文字
        String logoText = "阿 正";
        String targerTextPath2 = "C:\\Users\\Administrator\\Desktop\\123123.jpg";
        System.out.println ("给图片添加水印文字开始...");
        // 给图片添加正水印文字
        ImageWatermarkUtil.ImageByText (logoText, srcImgPath, targerTextPath2, -40);
        // 给图片添加斜水印文字
        ImageWatermarkUtil.ImageByText (logoText, srcImgPath, targerTextPath2, -40);
        System.out.println ("给图片添加水印文字结束...");
    }
}

 

要在Java实现倾斜的水印铺满整张图片,可以使用Graphics2D类的rotate()方法和drawString()方法。 下面是一个实现的示例代码: ```java import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Watermark { public static void main(String[] args) throws Exception { // 读取原 BufferedImage image = ImageIO.read(new File("original.jpg")); // 创建一个新的 BufferedImage,大小与原相同 BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); // 获取 Graphics2D 对象,用于绘制水印 Graphics2D g2d = newImage.createGraphics(); // 将水印旋转 45 度 AffineTransform at = new AffineTransform(); at.rotate(Math.toRadians(45), image.getWidth() / 2, image.getHeight() / 2); g2d.setTransform(at); // 设置水印字体、颜色、大小 g2d.setFont(new Font("微软雅黑", Font.BOLD, 20)); g2d.setColor(Color.WHITE); // 计算水印文字的宽度、高度 String watermark = "watermark"; FontMetrics fm = g2d.getFontMetrics(); int textWidth = fm.stringWidth(watermark); int textHeight = fm.getHeight(); // 计算水印文字的起始位置 int startX = -textWidth / 2; int startY = image.getHeight() / 2; // 循环绘制水印,直到铺满整张 int x = startX; int y = startY; while (y < image.getHeight() + textHeight) { g2d.drawString(watermark, x, y); x += textWidth; if (x > image.getWidth() + textWidth) { x = startX; y += textHeight; } } // 释放 Graphics2D 对象 g2d.dispose(); // 保存新 ImageIO.write(newImage, "jpg", new File("watermarked.jpg")); } } ``` 在这个示例中,我们首先读取了一张原始的图片,然后创建了一个新的 BufferedImage 对象,大小与原相同。接着,我们获取 Graphics2D 对象,并使用 AffineTransform 类将水印旋转了 45 度。然后,我们设置了水印的字体、颜色、大小,并计算出了水印文字的宽度和高度。最后,我们使用循环绘制水印,并在绘制的过程中断调整水印的位置,直到铺满整张。最后,我们将新保存到文件中。 注意,这个示例只是一个简单的实现,实际上还有很多细节需要注意。比如,当水印文字倾斜时,它的宽度和高度可能会发生变化,因此我们需要重新计算起始位置。此外,如果原是 PNG 格式等支持透明度的图片,我们还需要考虑如何处理透明度。总之,在实际应用中,我们需要根据具体情况进行调整和优化。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值