How to Correctly Overlay Text onto a BufferedImage using Java\'s Graphics2D?
Using Graphics2D to Overlay Text on a BufferedImage and Return a BufferedImage
In this example, we demonstrate how to overlay text on a BufferedImage using Graphics2D. We aim to provide a solution for rendering the text directly onto the image and returning the modified BufferedImage.
Initial Code and Discrepancy:
The provided code snippet attempted to achieve the text overlay but failed to make any visible changes to the image.
Issue:
The issue lies in how the drawString() method interprets the x and y coordinates. These coordinates denote the position of the baseline of the first character, not the top-left corner of the text. Therefore, depending on the font and the presence of descenders (characters like "g" or "p"), the text may end up outside the image bounds.
Solution:
To address this, we need to adjust the positioning of the text. Instead of using x and y directly, we first obtain the FontMetrics for the current Font object. The FontMetrics allows us to calculate the necessary offsets to position the text correctly.
Specifically, we compute the horizontal offset to ensure that the text is centered within the available width, and we adjust the vertical offset to avoid clipping the text.
Rewritten Code with Example:
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class TextOverlay extends JPanel { private BufferedImage image; public TextOverlay() { try { image = ImageIO.read(new URL( "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png")); } catch (IOException e) { e.printStackTrace(); } image = process(image); } @Override public Dimension getPreferredSize() { return new Dimension(image.getWidth(), image.getHeight()); } private BufferedImage process(BufferedImage old) { int w = old.getWidth() / 3; int h = old.getHeight() / 3; BufferedImage img = new BufferedImage( w, h,BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.drawImage(old, 0, 0, w, h, this); g2d.setPaint(Color.red); g2d.setFont(new Font("Serif", Font.BOLD, 20)); String s = "Hello, world!"; FontMetrics fm = g2d.getFontMetrics(); int x = img.getWidth() - fm.stringWidth(s) - 5; int y = fm.getHeight(); g2d.drawString(s, x, y); g2d.dispose(); return img; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); } private static void create() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new TextOverlay()); f.pack(); f.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { create(); } }); } }
In this modified code, we properly calculate the offsets based on the font metrics and render the text accordingly. As a result, the overlay text will be correctly positioned within the image.
The above is the detailed content of How to Correctly Overlay Text onto a BufferedImage using Java\'s Graphics2D?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...
