How can I watermark an image in Java?

Pit Digger picture Pit Digger · Mar 28, 2011 · Viewed 41.5k times · Source

How can I create a watermark over an image using Java? I need user-entered text to be added to a provided position over an image. Any sample code/suggestions will help.

Answer

coobird picture coobird · Mar 28, 2011

In Thumbnailator, one can add a text caption to an existing image by using the Caption image filter:

// 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);

In the above code, the text Hello World will be drawn on centered on the originalImage with a Monospaced font, with a black foreground color, at 14 pt.

Alternatively, if a watermark image is to be applied to an existing image, one can use the Watermark image filter:

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

Watermark filter = new Watermark(Positions.CENTER, watermarkImage, 0.5f);
BufferedImage watermarkedImage = filter.apply(originalImage);

The above code will superimpose the watermarkImage on top of the originalImage, centered with an opacity of 50%.

Thumbnailator will run on plain old Java SE -- one does not have to install any third party libraries. (However, using the Sun Java runtime is required.)

Full disclosure: I am the developer for Thumbnailator.