Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

How to convert BufferedImage to image to display on JSP

I would like to convert BufferedImage to an image that will display on JSP page. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 an URL pattern of /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 Files#copy() with ImageIO#write().

response.setContentType("image/png");
ImageIO.write(bufferedImage, "png", response.getOutputStream());

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:

ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", output);
String imageAsBase64 = Base64.getEncoder().encodeToString(output.toByteArray());
request.setAttribute("imageAsBase64", imageAsBase64);
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);

And finally show it in the forwarded JSP using the data URI scheme as below:

<img src="data:image/png;base64,${imageAsBase64}" />

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...