Using Graphics2D to Add Text Overlays on a BufferedImage
This question pertains to the overlaying of text onto a BufferedImage using Graphics2D. The aim is to render the final image with the added text.
Problem Description
The provided code snippet attempts to overlay text at specific coordinates using Graphics2D:
protected BufferedImage Process2(BufferedImage image){ Graphics2D gO = image.createGraphics(); gO.setColor(Color.red); gO.setFont(new Font( "SansSerif", Font.BOLD, 12 )); gO.drawString(this.text, this.x, this.y); System.err.println(this.text+this.x+this.y); return image; }
However, the output image remains unaltered.
Solution
1. Baseline for Text Rendering:
2. Image Color Model Compatibility:
Revised Code Using Rendered Text on Image:
import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; public class TextOverlay { public static BufferedImage process(BufferedImage image, String text, int x, int y) { int w = image.getWidth(); int h = image.getHeight(); BufferedImage processed = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); // Create Graphics2D object for the processed image Graphics2D g2 = processed.createGraphics(); // Transfer the contents of the original image to the processed image g2.drawImage(image, 0, 0, w, h, null); // Set the text color and font g2.setColor(Color.red); Font font = new Font("SansSerif", Font.BOLD, 12); g2.setFont(font); // Get the font metrics to determine the bounding box for the text FontMetrics fm = g2.getFontMetrics(font); int textWidth = fm.stringWidth(text); int textHeight = fm.getAscent() - fm.getDescent(); // Calculate the coordinates for the text so that it is centered at the specified location int textX = x - textWidth / 2; int textY = y + textHeight / 2; // Draw the text on the processed image g2.drawString(text, textX, textY); // Dispose of the Graphics2D object g2.dispose(); return processed; } }
Usage:
BufferedImage image = ... // Load your original image String text = "Hello, world!"; int x = 100; int y = 100; BufferedImage processedImage = TextOverlay.process(image, text, x, y); // Use the processed image as needed
The above is the detailed content of How to Correctly Overlay Text onto a BufferedImage using Graphics2D?. For more information, please follow other related articles on the PHP Chinese website!