views:

459

answers:

1

Hello friends, I want to convert BufferedImage to Image so that it will display on JSP page.

+3  A: 

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 the src attribute point to an URL. E.g.

<img src="url/to/image.jpg">

(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 Servlet which listens on the url-pattern matching the image URL. E.g.

<img src="imageservlet/image.jpg">

(here the servlet is obviously to be mapped on /imageservlet/* and the image identifier, here the filename, is here available by request.getPathInfo())

The <img src> will fire a GET request, so you just have to implement doGet() method of the servlet. To send a HTTP response all you need to do is to write some content to the OutputStream of the response, along with a set of response headers representing the content (Content-Type, Content-Length and/or Content-disposition). You can use ImageIO#write() to write a BufferedImage to an OutputStream.

You can find a basic example of such an image servlet here. You just have to replace InputStream --> OutputStream write loop with ImageIO#write().

BalusC