java文字水印模糊_Java添加文字水印和图片水印
时间: 2023-08-19 16:14:08 浏览: 234
好的,我了解了您的问题。您可以使用Java的Graphics2D类来添加文字水印和图片水印。以下是一个简单的例子:
```java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Watermark {
public static void main(String[] args) {
try {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File("original.png"));
// 创建带有透明度的图片
BufferedImage watermarkedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
// 获取 Graphics2D 对象
Graphics2D g2d = (Graphics2D) watermarkedImage.getGraphics();
// 在图片上绘制原始图片
g2d.drawImage(originalImage, 0, 0, null);
// 设置文字水印
String text = "Watermark Text";
Font font = new Font("Arial", Font.BOLD, 48);
g2d.setFont(font);
g2d.setColor(Color.WHITE);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(text, g2d);
g2d.drawString(text, (originalImage.getWidth() - (int) rect.getWidth()) / 2, originalImage.getHeight() / 2);
// 设置图片水印
BufferedImage watermarkImage = ImageIO.read(new File("watermark.png"));
int x = originalImage.getWidth() - watermarkImage.getWidth() - 10;
int y = originalImage.getHeight() - watermarkImage.getHeight() - 10;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.drawImage(watermarkImage, x, y, null);
// 保存水印图片
ImageIO.write(watermarkedImage, "png", new File("watermarked.png"));
// 释放资源
g2d.dispose();
System.out.println("Watermark applied.");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
```
您可以根据您的需求调整文字和图片的位置、大小、透明度等参数以实现您想要的效果。希望能对您有所帮助!
阅读全文