tags:

views:

908

answers:

2

Hi All :
I have ByteArrayOutputStream which contains a jpeg image in bytes. My requirement is to display that image in jsp page(to display the image in front end using html tags). How do i do that?.

I have refrred BufferedImage class but it confusing for me because i am new to this.. Please help me.. Thanks in advance.

+3  A: 

Unless you use a "data" URI (useful for small images) the browser will make two requests: one for the HTML and one for the image. You need to be able to output an img tag which includes enough information to let you respond to the subsequent request for the image with the data in your ByteArrayOutputStream.

Depending on how you got that jpeg and how your server scales out, that might involve writing the image to disk, caching it in memory, regenerating it, or any combination of these.

If you can delay the image generation until the browser requests the actual image in the first place, that's pretty ideal. That may involve putting extra parameters in the URL for the image - such as points on a graph, or the size of thumbnail to generate, or whatever your image is.

If you're new to both JSP and HTML, I strongly recommend you concentrate on the HTML side first. Work out what you need to serve and what the browser will do before you work out how to serve it dynamically. Start with static pages and files for the HTML and images, and then work out how to generate them instead.

Jon Skeet
+5  A: 

if the image is not too big you can do it as follows:

<img src="data:image/jpg;base64,iVBORw0KGgoAAAANS..." />

where iVBORw0KGgoAAAANS... is the base 64 encoded bytes

base 64 encoding can be done with a library, like this or this

Andreas Petersson
this method inlines the image into the html that is being rendered which can also increase the file size
Ram
My image is very small only.. Its a barcode image of size width="166" height="44".. In the above, how do i get image from ByteArrayOutputStream?
166x44 isn't exactly "very small" (usually data URIs are used for really tiny images) but with a bar code you may get away with it. Basically you need to base64 encode the data. That's a separate, very specific question - which has probably already been covered elsewhere on Stack Overflow.
Jon Skeet
From a ByteArrayInputStream, and using Commons :List aList = new ArrayList<Byte>();int cByte = bais.read();while (cByte != null){aList.add(cByte);cByte = bais.read();}byte[] result = Base64.encode(aList.toArray());String imageData = new String(result)And you can use imageData.
Valentin Rocher