1. 首页
  2. 课程学习
  3. Java
  4. Java实现图片加水印的简易方法

Java实现图片加水印的简易方法

上传者: 2023-03-08 07:28:46上传 PDF文件 12.29MB 热度 8次
// Java实现图片加水印的简易方法
import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Watermark {
    public static void main(String[] args) throws IOException {
        // 读取原图片
        BufferedImage sourceImage = ImageIO.read(new File("source.jpg"));

        // 创建一个图片缓存对象
        BufferedImage targetImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_RGB);

        // 创建一个绘制对象
        Graphics2D graphics = targetImage.createGraphics();

        // 在绘制对象上设置渲染属性
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);

        // 将原图片绘制到缓存图片上
        graphics.drawImage(sourceImage, 0, 0, null);

        // 在缓存图片上添加水印
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        graphics.setFont(new Font("宋体", Font.BOLD, 48));
        graphics.drawString("水印文字", 100, 100);

        // 保存添加水印后的图片
        ImageIO.write(targetImage, "jpg", new File("target.jpg"));
    }
}
用户评论