Showing posts with label watermark text. Show all posts
Showing posts with label watermark text. Show all posts

Saturday, May 16, 2015

Java Create Watermark Text Or Fill Area To An Image


package com.pkm;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class WatermarkTextToImage {
    public static void main(String[] args) throws Exception {
 ImageIcon photo = new ImageIcon("100_6929.jpg");
 BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
  photo.getIconHeight(),
  BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

        g2d.drawImage(photo.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, 100));

        String watermark = "Pritom Kumar Mondal";

        FontMetrics fontMetrics = g2d.getFontMetrics();
        Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

        g2d.drawString(watermark,
         (photo.getIconWidth() - (int) rect.getWidth()) / 2,
         (photo.getIconHeight() - (int) rect.getHeight()) / 2);

        alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f);
        g2d.setComposite(alpha);
        g2d.setColor(Color.red);
        g2d.fillOval(0, 0, photo.getIconWidth(), photo.getIconHeight());

        //Free graphic resources
        ImageIO.write(bufferedImage, "JPEG", new File("100_6929_Watermark.JPG"));
        g2d.dispose();
    }
}

Input & Output Image Respectively