Java Image Watermarking
A watermarking is a technique that allows an individual to add copyright notices or other verification messages to digital audio, video, or image signals and documents. It may be visible, hidden, or a combination of both. In this section, you will learn how to watermark an image using java swing.
Here is the code:
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.ImageIcon;
import java.awt.geom.Rectangle2D;
public class ImageWatermarking {
public static void main(String[] args) {
try {
File file = new File("C:/rose.jpg");
if (!file.exists()) {
System.out.println("File not Found");
}
ImageIcon icon = new ImageIcon(file.getPath());
BufferedImage bufferedImage = new BufferedImage(
icon.getIconWidth(), icon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.drawImage(icon.getImage(), 0, 0, null);
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.5f);
g2d.setComposite(alpha);
g2d.setColor(Color.white);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setFont(new Font("Arial", Font.BOLD, 30));
String watermark = "Hello World";
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);
g2d.drawString(watermark, (icon.getIconWidth() - (int) rect
.getWidth()) / 2, (icon.getIconHeight() - (int) rect
.getHeight()) / 2);
g2d.dispose();
File fileout = new File("C:/watermarkedImage.jpg");
ImageIO.write(bufferedImage, "jpg", fileout);
} catch (IOException ioe) {
}
}
}
Output:
![]() |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.