>Java >java지도 시간 >Graphics2D를 사용하여 BufferedImage에 텍스트를 올바르게 오버레이하는 방법은 무엇입니까?

Graphics2D를 사용하여 BufferedImage에 텍스트를 올바르게 오버레이하는 방법은 무엇입니까?

DDD
DDD원래의
2024-12-21 12:49:091100검색

How to Correctly Overlay Text onto a BufferedImage using Graphics2D?

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. 텍스트 렌더링을 위한 기준선:

  • Graphics2D의 drawString() 메서드는 지정된 좌표를 가장 왼쪽 문자의 기준선으로 해석합니다. 이는 소문자나 숫자의 디센더와 같이 기준선 아래로 확장되는 문자가 포함된 경우 텍스트가 이미지 외부에 렌더링될 수 있음을 의미합니다.

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.