I am creating a method in Java Spring that should return an image that contains a text in a transparent background. I have been searching for a while but I can't find the answer.
I assume that a good way this image is using Graphics2D
but I can't find the magic formula. The following example doesn't work:
@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();
}
There are a couple of problems. Firstly, you need to create an image buffer that can support alpha:
BufferedImage image = new BufferedImage(200, 40, BufferedImage.TYPE_INT_ARGB);
Secondly, after clearing the background you forgot to set the compositing rule back to SrcOver
. However, there's no need to clear the background (it is initialised to transparent), so we can just leave that step out.
The with corrections (and an added antialiasing hint) the code looks like this:
@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);
}