2

I have an image on top of which I need to add different text based on url parameter. I'm planning to do this with Graphics2D/BufferedImage.

The question is, do I have to save image to disk in order to show it in JSP to the user? The purpose of the image is only be displayed and I'd rather not to save thousands of the images that will be generated...

Thanks!

Myroslav Tedoski
  • 301
  • 3
  • 14
  • 1
    No, you don't have to physically save the image to the file system. Just write the image data to the page's output stream and send the appropriate content type. [This answer](http://stackoverflow.com/questions/18886287/how-to-display-image-in-html-using-jsp-call/18910756#18910756) might help. – sgbj Jan 22 '16 at 20:29
  • 1
    @sbat Although that does work, my only complaint with that answer is that there is no reason to implement the image page (Chart.jsp) as a JSP page. That should really be a plain old Servlet. – matt forsythe Jan 22 '16 at 20:36
  • @mattforsythe Agreed, a Servlet would be the most appropriate way to implement it, but the concept remains the same. – sgbj Jan 22 '16 at 20:40
  • @sbat Correct. In fact, the code in that solution is exactly the code I recommend. – matt forsythe Jan 22 '16 at 20:45

2 Answers2

5

You do not have to save the image to disk. You can use a bare-bones vanilla servlet to generate the BufferedImage, and then use ImageIO.write() to write that image to the response.getOutputStream(). Just make sure you set the headers to the correct content-type. Then, in the HTML generated by the JSP, just use the URL of the servlet as the src for the img tag.

matt forsythe
  • 3,863
  • 1
  • 19
  • 29
1

You can base64 encode the image and chuck it onto the page. Browsers won't cache it, though.

Embedding Base64 Images

https://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

Community
  • 1
  • 1
Andreas
  • 4,937
  • 2
  • 25
  • 35