分为文字水印和透明图片水印
package com.qms.report.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageWatermark {
/**
* @param waterMarkType 1时代表水印是文本,2代表水印是透明图片
*/
private void imageWatermark(int waterMarkType) {
// 原始图片路径
String imagePath = "/Users/jaki/Desktop/BSQ/QMS/QMS/qms-qc-report/src/main/java/com/qms/report/util/images.jpg";
// 书印文字
String watermarkText = "Your Watermark";
// 书印透明图片地址
String watermarkImagePath = "path_to_watermark_image.png";
// 输出路径
String outputImagePath = "/Users/jaki/Desktop/BSQ/QMS/QMS/qms-qc-report/src/main/java/com/qms/report/util/imagesRemark.jpg";
try {
// 原始图片
BufferedImage originalImage = ImageIO.read(new File(imagePath));
// 副本(水印)图片
BufferedImage watermarkedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);
// 获取图形
Graphics2D graphics = (Graphics2D) watermarkedImage.getGraphics();
// 绘制图片
graphics.drawImage(originalImage, 0, 0, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
if (waterMarkType == 1) {
// 1时代表水印是文本
// 字体
Font font = new Font("Arial", Font.BOLD, 36);
graphics.setFont(font);
graphics.setColor(Color.RED);
// 获取指定字体的规格
FontMetrics fontMetrics = graphics.getFontMetrics(font);
int textwidth = fontMetrics.stringWidth(watermarkText);
int textheight = fontMetrics.getHeight();
int x = (originalImage.getWidth() - textwidth);
int y = (originalImage.getHeight() - textheight);
// 绘制水印
graphics.drawString(watermarkText, x, y);
} else {
// 读取水印图片
BufferedImage watermarkImage = ImageIO.read(new File(watermarkImagePath));
int x = (originalImage.getWidth() - watermarkImage.getWidth());
int y = (originalImage.getHeight() - watermarkImage.getHeight());
graphics.drawImage(watermarkImage, x, y, null);
}
ImageIO.write(watermarkedImage, "jpg", new File(outputImagePath));
graphics.dispose();
System.out.println("添加水印结束!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
}
}
标签:originalImage,Java,int,BufferedImage,水印,加水,graphics,new,图片
From: https://www.cnblogs.com/Retired-lad/p/17542181.html