如何将BufferedImage转换为图像以在JSP上显示 [英] How to convert BufferedImage to image to display on JSP
问题描述
我想将 BufferedImage
转换为将在JSP页面上显示的图像。我怎样才能实现这个目标?
I would like to convert BufferedImage
to an image that will display on JSP page. How can I achieve this?
推荐答案
首先,JSP是一种视图技术,提供了一个模板来编写HTML / CSS / JS和能够与后端Java代码交互以控制页面流和访问后端数据。你的问题更多的是HTML。
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.
现在,要在HTML页面中显示图像,您需要HTML < img>
元素。要定义/分配图像,您只需要让 src
属性指向一个URL。例如,
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">
(它可以相对于当前上下文,也可以是绝对URL,例如以<$开头) c $ c> http:// )
(it can be either relative to the current context, or an absolute URL, e.g. starting with http://
)
如果图像是动态的,就像你的情况一样,你需要一个 Servlet
,它侦听匹配图像URL的 url-pattern
。例如,
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">
(这里的servlet显然要映射到 / imageservlet / *
和图像标识符,这里是文件名,在这里可以通过 request.getPathInfo()
)
(here the servlet is obviously to be mapped on /imageservlet/*
and the image identifier, here the filename, is here available by request.getPathInfo()
)
< img src>
将触发GET请求,因此您只需实现 doGet()
servlet的方法。要发送HTTP响应,您需要做的就是将一些内容写入响应的 OutputStream
,以及一组代表内容的响应头( Content-Type
, Content-Length
和/或 Content-disposition
)。您可以使用 ImageIO#write()
写一个 BufferedImage
到 OutputStream
。
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
.
您可以找到这种图像servlet的基本示例这里。您只需要用 Files#copy() /ImageIO.html#write-java.awt.image.RenderedImage-java.lang.String-java.io.OutputStream-rel =nofollow noreferrer> ImageIO#write()
。
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());
参见:
- 如何从JSP页面中的数据库中检索和显示图像?
- 在Java Web应用程序中从应用程序服务器外部提供静态数据的最简单方法
- How to retrieve and display images from a database in a JSP page?
- Simplest way to serve static data from outside the application server in a Java web application
See also:
这篇关于如何将BufferedImage转换为图像以在JSP上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!