Search code examples
javaspring-bootbufferedimagegraphics2dwatermark

Add rotated watermark text with background to image in Java


I am using Java 8 (Spring Boot), and I want to add text (as watermark) to an image like this:

example

As you see, the text HELLO WORLD! is rotated 90 degrees, and it has black background color (the grey background is a source image).

Here is my current Java code that adds text to an image in center (no background, not rotated):

public BufferedImage AddTextWatermarkInCenter(BufferedImage targetImg, String watermarkText) {
    Graphics2D targetImgGraphics = (Graphics2D)targetImg.getGraphics();
    
    // Init graphic properties
    AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
    targetImgGraphics.setComposite(alphaComposite);
    targetImgGraphics.setColor(Color.BLACK);
    targetImgGraphics.setFont(WatermarkImageHelper.AcquireWatermarkFont());
    
    FontMetrics targetImgFontMetrics = targetImgGraphics.getFontMetrics();
    Rectangle2D targetImgRectangle = targetImgFontMetrics.getStringBounds(watermarkText, targetImgGraphics);
    
    // Calculates the coordinate where the text is painted
    int centerX = ((targetImg.getWidth() - (int)targetImgRectangle.getWidth()) / 2);
    int centerY = (targetImg.getHeight() / 2);
    
    // Paints the textual watermark
    targetImgGraphics.drawString(watermarkText, centerX, centerY);
    
    targetImgGraphics.dispose();
    
    return targetImg;
}

How do I draw watermark text as the example image?


Solution

  • You can use an AffineTransform to rotate the Graphics.

    For example:

    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    
    public class Rotate extends JPanel
    {
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
    
            Graphics2D g2 = (Graphics2D)g.create();
    
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
            g2.setFont( new Font( "Helvetica", Font.BOLD, 12 ) );
    
            for( double angle = 0; angle <= 90; angle+=30 )
            {
                String text = "Rotate angle is " + (int)angle;
                AffineTransform af = new AffineTransform();
                af.translate(50, 50);
                af.rotate( Math.toRadians( angle ) );
                g2.setTransform( af );
    
                g2.setColor( Color.black );
                g2.drawString(text, 50, 0);
                g2.setColor( Color.red );
                g2.drawLine(0, 0, 200, 0 );
            }
    
            g2.dispose();
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return new Dimension(300, 300);
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("Rotate");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Rotate());
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args) throws Exception
        {
            java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
        }
    }