Here you can find the source of waterMarkImage(final BufferedImage image, final String text)
Parameter | Description |
---|---|
image | Image to be watermarked |
text | text to be used as a watermark. |
public static BufferedImage waterMarkImage(final BufferedImage image, final String text)
//package com.java2s; //License from project: Apache License 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; public class Main { /**//from ww w . ja va2 s .c om * Watermarks the given image with given text. * @param image Image to be watermarked * @param text text to be used as a watermark. * @return new watermarked image. */ public static BufferedImage waterMarkImage(final BufferedImage image, final String text) { if (image == null) { throw new IllegalArgumentException("\"image\" param cannot be null."); } // create a new image final BufferedImage waterMarked = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); final Graphics2D imageG = waterMarked.createGraphics(); // draw original image. imageG.drawImage(image, null, 0, 0); imageG.dispose(); final Graphics2D g = waterMarked.createGraphics(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); // 50% transparency g.setColor(Color.white); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setFont(new Font("Arial", Font.BOLD, 30)); final FontMetrics fontMetrics = g.getFontMetrics(); final Rectangle2D rect = fontMetrics.getStringBounds(text, g); final int centerX = (image.getWidth() - (int) rect.getWidth()) / 2; final int centerY = (image.getHeight() - (int) rect.getHeight()) / 2; g.drawString(text, centerX, centerY); g.dispose(); return waterMarked; } }