使用Java在图像上写多行文本(自动换行)

时间:2019-02-19 11:45:42

标签: java image swing text

我有一些图像需要编写,每个文本顶部的多行文本居中对齐,如下所示。我也尝试了StackOverflow的一些代码,但无法使居中工作。我发现有些人也有同样的问题,但是我没有找到任何解决方案。有人可以帮助我吗?我将不胜感激。 谢谢!

图片enter image description here

以下是我尝试过的示例

Generate image files

Write text on the image

Split text to parts and place on the image

这个人也帮不了我

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class AddTextWatermark {

    public static void main(String... args) throws IOException {

        // overlay settings
        String text = "I am in Stackoverflow Now!"; //This is short text. How can I wrap long text and place text centered?
        File input = new File("./src/1.jpg");
        File output = new File("./src/2.jpg");

        // adding text as overlay to an image
        addTextWatermark(text, "jpg", input, output);
    }

    private static void addTextWatermark(String text, String type, File source, File destination) throws IOException {
        BufferedImage image = ImageIO.read(source);

        // determine image type and handle correct transparency
        int imageType = "png".equalsIgnoreCase(type) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
        BufferedImage watermarked = new BufferedImage(image.getWidth(), image.getHeight(), imageType);

        // initializes necessary graphic properties
        Graphics2D w = (Graphics2D) watermarked.getGraphics();
        w.drawImage(image, 0, 0, null);
        AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
        w.setComposite(alphaChannel);
        w.setColor(Color.GRAY);
        w.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 26));
        FontMetrics fontMetrics = w.getFontMetrics();
        Rectangle2D rect = fontMetrics.getStringBounds(text, w);

        // calculate center of the image
        int centerX = (image.getWidth() - (int) rect.getWidth()) / 2;
        int centerY = image.getHeight() / 2;

        // add text overlay to the image
        w.drawString(text, centerX, centerY);
        ImageIO.write(watermarked, type, destination);
        w.dispose();
    }


}

0 个答案:

没有答案