Help getting image from Servlet to JSP page [duplicate]

I currently have to generate an image that displays the text of a string, i need to make this image on a Servlet and then somehow pass the image to a JSP page so that it can display it. I'm trying to avoid saving the image, and instead somehow stream the image to the JSP.

I haven't found a way of generating the image since i started with finding how to pass an image from the Servlet to the JSP adn got stuck.

EDIT: The jsp page is already made and isn't created by the servlet, i have to pass the image into an already existing jsp

Any help is appreciated.


You need to write the image as a byte array to the response's output stream. Something like this:

byte[] imageBytes = getImageAsBytes();

response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);

response.getOutputStream().write(imageBytes);

Then in you JSP you just use a standard img element:

<img src="url to your servlet">

You can't1 return both in the same response, since you're returning different types (an HTML page of type text/html and an image of type image/jpeg, say).

For this sort of thing, I will generate the image during the initial servlet request (for the containing HTML page). I store it in a cache in my servlet, and write the HTML page with the image tag containing a URL to that image with the handle.

e.g. the browser asks for http://whatever/page

The servlet generates the image, and writes an HTML tag in the page like

<img src="http://whatever/image/unique_handle_to_image">

The browser will render the HTML page, and as part of that issue a new request to my servlet with the handle for the image.

e.g. the browser now asks for http://whatever/image/unique_handle_to_image

I then return the image as content type image/jpeg or similar.

So you have two requests going on. One for the page, in which you render the image and store it temporarily, and the second in which you return the image. You have to remember to clear the image cache, but that's all straightforward. I wouldn't worry about storing lots of images, since the two requests from the browser usually (!) come in quick succession.

  1. I guess it's possible to use a data uri provided your browser supports it, and create something like

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
    

Note there are a number of caveats surrounding these. See the linked page.