Raja D
Raja D

Reputation:

How to display an image which is in bytes to JSP page using HTML tags?

I have ByteArrayOutputStream which contains a JPEG image in bytes. My requirement is to display that image in a JSP page (to display the image in the frontend using HTML tags). How do I do that?

I have referred the BufferedImage class, but it is confusing for me because I am new to this.

Upvotes: 4

Views: 19473

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500785

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 file 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.

Upvotes: 3

Andreas Petersson
Andreas Petersson

Reputation: 16518

If the image is not too big, you can do it as follows.

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

Where iVBORw0KGgoAAAANS... is the Base64 encoded bytes.

Base64 encoding can be done with a library, like Ostermiller Java Utilities' Base64 Java Library or org.apache.commons.codec.binary.Base64.

Upvotes: 19

Related Questions