I would like to convert BufferedImage to an image that will display on JSP page. How can I achieve this?
I would like to convert BufferedImage to an image that will display on JSP
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, JSP is a view technology providing a template to write HTML/CSS/JS in and the ability to interact with backend Java code to control page flow and access backend data. Your problem is more in HTML.
Now, to display an image in a HTML page, you need the HTML
<img>element. To define/allocate an image, you just have to let thesrcattribute point to an URL. E.g.(it can be either relative to the current context, or an absolute URL, e.g. starting with
http://)If the image is dynamic, as in your case, you need to have a
Servletwhich listens on theurl-patternmatching the image URL. E.g.(here the servlet is obviously to be mapped on an URL pattern of
/imageservlet/*and the image identifier, here the filename, is here available byrequest.getPathInfo())The
<img src>will fire a GET request, so you just have to implementdoGet()method of the servlet. To send a HTTP response all you need to do is to write some content to theOutputStreamof the response, along with a set of response headers representing the content (Content-Type,Content-Lengthand/orContent-disposition). You can useImageIO#write()to write aBufferedImageto anOutputStream.You can find a basic example of such an image servlet here. You just have to replace
Files#copy()withImageIO#write().As a completely different alternative, you can also let the servlet convert the image to a Base64 encoded string and pass it on to the JSP:
And finally show it in the forwarded JSP using the data URI scheme as below:
You only need to keep in mind that this doesn’t give the server nor the client the opportunity to cache the image. So this approach is plain inefficient in case the image is not temporary.
See also: