在Java中向图像添加带背景的旋转水印文字

huangapple go评论66阅读模式
英文:

Add rotated watermark text with background to image in Java

问题

public BufferedImage AddTextWatermarkAsExample(BufferedImage targetImg, String watermarkText) {
    Graphics2D targetImgGraphics = (Graphics2D) targetImg.getGraphics();
    
    // Initialize 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);
    
    // Calculate the coordinate where the text is painted
    int centerX = targetImg.getWidth() / 2;
    int centerY = ((targetImg.getHeight() - (int) targetImgRectangle.getWidth()) / 2);
    
    // Rotate the graphics context by 90 degrees
    targetImgGraphics.rotate(Math.toRadians(90), centerX, centerY);
    
    // Paint the textual watermark with a black background
    int textX = centerY; // Adjusted for rotation
    int textY = -(int) targetImgRectangle.getHeight() - centerX; // Adjusted for rotation
    targetImgGraphics.fillRect(textX, textY, (int) targetImgRectangle.getHeight(), (int) targetImgRectangle.getWidth());
    targetImgGraphics.setColor(Color.WHITE); // Set the text color
    targetImgGraphics.drawString(watermarkText, textX, textY + (int) targetImgRectangle.getWidth());
    
    targetImgGraphics.dispose();
    
    return targetImg;
}

This modified Java code will draw the watermark text as shown in the example image with a 90-degree rotation and a black background.

英文:

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

在Java中向图像添加带背景的旋转水印文字

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?

答案1

得分: 2

你可以使用AffineTransform来旋转图形。

例如:

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 = "旋转角度为 " + (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("旋转");
        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() );
    }
}
英文:

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( &quot;Helvetica&quot;, Font.BOLD, 12 ) );
for( double angle = 0; angle &lt;= 90; angle+=30 )
{
String text = &quot;Rotate angle is &quot; + (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(&quot;Rotate&quot;);
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( () -&gt; createAndShowGUI() );
}
}

huangapple
  • 本文由 发表于 2023年2月10日 05:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定