透明背景上的纯文本

Solid text over transparent background

我正在 Java Spring 中创建一个方法,该方法应该 return 包含透明背景文本的图像。我已经搜索了一段时间,但找不到答案。

我认为这张图片使用 Graphics2D 的好方法,但我找不到神奇的公式。以下示例不起作用:

@RequestMapping(value= "/test", method = RequestMethod.GET)
public void dynamicImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setContentType("image/jpg");

    ServletOutputStream out = response.getOutputStream();

    BufferedImage image = new BufferedImage(200, 40, BufferedImage.TYPE_BYTE_INDEXED);

    Graphics2D graphics = image.createGraphics();
    graphics.setComposite(AlphaComposite.Clear);
    graphics.fillRect(0,0, 200, 40);

    // I know ... I am using Comic Sans for testing ...
    Font font = new Font("Comic Sans MS", Font.BOLD, 30);
    graphics.setFont(font);

    graphics.setColor(Color.RED);

    graphics.drawString("Hello World!", 5, 30);

    graphics.dispose();

    // Use PNG Decoder
    //JPEGCodec.createJPEGEncoder(out).encode(image);

    out.close();
}

有几个问题。首先,您需要创建一个可以支持alpha的图像缓冲区:

BufferedImage image = new BufferedImage(200, 40, BufferedImage.TYPE_INT_ARGB);

其次,清除背景后忘记将合成规则设置回SrcOver。但是,不需要清除背景(它被初始化为透明),所以我们可以忽略这一步。

经过更正(并添加了抗锯齿提示)的代码如下所示:

    @RequestMapping(value= "/test", method = RequestMethod.GET)
    public void dynamicImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        ServletOutputStream out = response.getOutputStream();

        // Create an image buffer that supports alpha
        BufferedImage image = new BufferedImage(200, 40, BufferedImage.TYPE_INT_ARGB);

        // Create a graphics context and turn antialiasing on
        Graphics2D graphics = image.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Comic Sans FTW
        Font font = new Font("Comic Sans MS", Font.BOLD, 30);
        graphics.setFont(font);
        graphics.setColor(Color.RED);
        graphics.drawString("Hello World!", 5, 30);

        // Dispose of the context
        graphics.dispose();

        // Encode to png
        ImageIO.write(image, "PNG", out);
    }