How to Add a Professional Watermark to Images Using Java

How to Add a Professional Watermark to Images Using Java

package com.deepsingh44;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class WatermarkExample {
    public static void main(String[] args) throws Exception {
        String inputFile="C:\\Users\\Deeps\\Downloads\\swan.JPG";
        String outputFile="D:\\swan.JPG";

        BufferedImage image = ImageIO.read(new File(inputFile));

        String name = "Deep Singh";
        String description = "Professional Photographer";

        Graphics2D g2d = image.createGraphics();

        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int padding = 15,x=20;
        int bottom = image.getHeight() - 20;

        Font nameFont = new Font("Arial", Font.BOLD, 28);
        Font descFont = new Font("Arial", Font.PLAIN, 20);

        FontMetrics nameMetrics = g2d.getFontMetrics(nameFont);
        FontMetrics descMetrics = g2d.getFontMetrics(descFont);

        int textWidth = Math.max(
                nameMetrics.stringWidth(name),descMetrics.stringWidth(description)
        );

        int textHeight = nameMetrics.getHeight() + descMetrics.getHeight();

        g2d.setComposite(
                AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)
        );

        g2d.setColor(Color.BLACK);

        g2d.fillRoundRect(
                x - padding,bottom - textHeight - padding,
                textWidth + padding * 2,textHeight + padding * 2,
                10,10
        );

        g2d.setComposite(
                AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)
        );

        g2d.setColor(Color.WHITE);

        int nameY = bottom - descMetrics.getHeight();

        g2d.setFont(nameFont);
        g2d.drawString(name, x, nameY);

        g2d.setFont(descFont);
        g2d.drawString(
                description,x,bottom
        );

        g2d.dispose();

        ImageIO.write(image,
                "JPG",new File(outputFile)
        );
    }
}

After adding the water mark in image below is the result.