如何在Java中为图像添加水印?

Pit*_*ger 12 java watermark image

如何使用Java在图像上创建水印?我需要将用户输入的文本添加到图像上的提供位置.任何示例代码/建议都会有所帮助.

coo*_*ird 10

Thumbnailator中,可以使用Caption图像过滤器为现有图像添加文本标题:

// Image to add a text caption to.
BufferedImage originalImage = ...;

// Set up the caption properties
String caption = "Hello World";
Font font = new Font("Monospaced", Font.PLAIN, 14);
Color c = Color.black;
Position position = Positions.CENTER;
int insetPixels = 0;

// Apply caption to the image
Caption filter = new Caption(caption, font, c, position, insetPixels);
BufferedImage captionedImage = filter.apply(originalImage);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,文本Hello WorldoriginalImage使用Monospaced字体居中绘制,黑色前景色为14 pt.

或者,如果要将水印图像应用于现有图像,可以使用Watermark图像过滤器:

BufferedImage originalImage = ...;
BufferedImage watermarkImage = ...;

Watermark filter = new Watermark(Positions.CENTER, watermarkImage, 0.5f);
BufferedImage watermarkedImage = filter.apply(originalImage);
Run Code Online (Sandbox Code Playgroud)

上面的代码将叠加watermarkImage在顶部originalImage,以50%的不透明度为中心.

Thumbnailator将在普通的旧Java SE上运行 - 一个不必安装任何第三方库.(但是,需要使用Sun Java运行时.)

完全披露:我是Thumbnailator的开发人员.