在透明背景的纯文本

时间:2016-11-17 05:05:08

标签: java graphics2d

我在Java Spring中创建一个方法,它应该返回一个包含透明背景文本的图像。我一直在寻找,但我找不到答案。

我认为这个图像使用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();
}

1 个答案:

答案 0 :(得分:2)

有几个问题。首先,您需要创建一个支持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);
    }