使用 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中文網其他相關文章!