使用 Graphics2D 在 BufferedImage 上添加文本叠加
此问题涉及使用 Graphics2D 将文本叠加到 BufferedImage 上。目的是使用添加的文本渲染最终图像。
问题描述
提供的代码片段尝试使用 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; }
但是,输出图像仍然存在不变。
解决方案
1.文本渲染的基线:
2.图像颜色模型兼容性:
在图像上使用渲染文本的修订代码:
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; } }
用法:
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
以上是如何使用 Graphics2D 将文本正确覆盖到 BufferedImage 上?的详细内容。更多信息请关注PHP中文网其他相关文章!