Originally posted by Ali Gohar:
I just wanted to show an image on the page on the fly. Don't want to store the image on disk first and then display it through html <img> tag. Want to create image in memory and write its bytes on JSP.
Usually, Image data (i.e. the bytes that make up a gif/jpg or whatever image) is not embedded in an html file. There is a link to an image URL in an HTML page. The browsers requests that image URL separately.
Now, if you want to generate image data from a JSP/Servlet, that's possible (as you have already seen). If you want to generate it from a custom tag, I think it is doable (even though it defeats the purpose of a JSP/Custom tags), but I haven't tried it -
1. The custom tag should be the first and the only data producing tag in the jsp page. For eg.
<@page import...%>
<mylib:img params/>
This is to ensure that no text is written to the output.
2. In the doStartTag(), use pageContext().getResponse().getOutputStream(); and then write the bytes to the output stream. I think
you should not bother about setting headers etc. at this time. Let the browser figure it out. Usually, browsers do figure out by looking at the datastream what it contains. If it works, try setting appropriate headers such as content type etc.
Please do let us know if it works
There is another way where you can actually embed image data in an HTML file.
You can write a javascript array in an html page and populate it with byte values. e.g.
<script language='javascript'>
var imgdata = {0x00, 0x49 ... }; //please look up correct javascript syntax.
</script>
Then onLoad() of body, you can use DHTML API (look up at MSDN), and instantiate the image object.
So basically, your JSP will be generating javascript code, which will be executed by the browser creating the image. This whole logic can be easily captured in a custom tag.
Many charting packages use this method of embedding images in a jsp page.