Graphics2D를 사용하여 버퍼링된 이미지에 텍스트 오버레이 추가
이 질문은 Graphics2D를 사용하여 버퍼링된 이미지에 텍스트를 오버레이하는 것과 관련됩니다. 목표는 추가된 텍스트로 최종 이미지를 렌더링하는 것입니다.
문제 설명
제공된 코드 조각은 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!