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();
}