Below code for add text water mark on image in JAVA:
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.itextpdf.awt.geom.Dimension;
public class TextWaterMarkOnImage {
public static void main(String[] args) {
try {
File sourceImageFile = new File("originalFilePath/original.jpg");
File destImageFile = new File("watermarkedFilePath/watermarked.png");
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f); //set transparency of watermark
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLACK);
Font font = new Font("Arial", Font.BOLD, 64); //font of text
g2d.setFont(font);
String text = "Checked"; //watermark text
Dimension dmDimension = getDimentionOfText(g2d, font, text);
int centerX = sourceImage.getWidth()/2 - (int)dmDimension.getWidth()/2;
int centerY = sourceImage.getHeight()/2 + (int)dmDimension.getHeight()/2;
// paints the textual watermark
g2d.drawString(text, centerX, centerY);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
System.out.println("The text watermark is added to the image.");
}catch (Exception e) {
// TODO: handle exception
}
}
public static Dimension getDimentionOfText(Graphics2D g2d, Font font , String text) {
// get metrics from the graphics
FontMetrics metrics = g2d.getFontMetrics(font);
// get the height of a line of text in this
// font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font
// and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the
// text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
System.out.println(size.getHeight() +" "+ size.getWidth());
return size;
}
}
No comments:
Post a Comment