如何将BufferedImage转换为图像以在JSP上显示

发布于 2024-08-25 09:04:30 字数 56 浏览 2 评论 0 原文

我想将 BufferedImage 转换为将在 JSP 页面上显示的图像。我怎样才能实现这个目标?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

救赎№ 2024-09-01 09:04:30

首先,JSP是一种视图技术,提供了编写HTML/CSS/JS的模板以及与后端Java代码交互以控制页面流和访问后端数据的能力。你的问题更多的是在 HTML 中。

现在,要在 HTML 页面中显示图像,您需要 HTML 元素。要定义/分配图像,您只需让 src 属性指向 URL。例如

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

(它可以是相对于当前上下文的,也可以是绝对 URL,例如以 http:// 开头)

如果图像是动态的,就像您的情况一样,您需要有一个 Servlet 监听与图像 URL 匹配的 url-pattern。例如

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

(此处 servlet 显然要映射到 /imageservlet/* 的 URL 模式,并且图像标识符(此处为文件名)可通过 request.getPathInfo() 获得>)

将触发 GET 请求,因此您只需实现 servlet 的 doGet() 方法。要发送 HTTP 响应,您需要做的就是将一些内容写入响应的 OutputStream 中,以及一组表示内容的响应标头 (Content-TypeContent-Length 和/或 Content-disposition)。您可以使用 ImageIO#write()BufferedImage 写入 OutputStream

您可以在此处找到此类图像 servlet 的基本示例。您只需将 Files#copy() 替换为 ImageIO#write()

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

作为完全不同的替代方案,您还可以让 servlet 将图像转换为 Base64 编码字符串并将其传递到 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);

最后使用 数据 URI 方案 如下:

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

您只需记住,这不会给服务器或客户端提供缓存图像的机会。因此,如果图像不是临时的,这种方法显然效率很低。


另请参阅:

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:

空气里的味道 2024-09-01 09:04:30

您无需将 BufferedImage 转换为 Image 即可将其显示在 jsp 页面上。因为,Java 6 JAXB 提供了 javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) String 将 byte[] 转换为 base 64 字符串嗯>。通过将源数据指定为 base 64,可以使用 html 标签显示 base 64 字符串src="data:image/jpg;。这是从 这篇文章

sample.jsp(测试通过):

<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
%>

<div>
    <p>As of v6, Java SE provides JAXB</p>
    <img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>          
</body>
</html>

IMO,这种方法非常适合小尺寸图像,例如thumbnail 否则使用图像的直接 url。在 src 属性中就可以了,例如:- No Profie Pic

You need not convert BufferedImage to Image to display it on the jsp page. Because, Java 6 JAXB provides javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) String to convert byte[] in to base 64 string. The base 64 string can be displayed using the <img html tag by specifying the source data as base 64 i.e. src="data:image/jpg;. Here is the sample program referred from this post.

sample.jsp (test passed) :

<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
%>

<div>
    <p>As of v6, Java SE provides JAXB</p>
    <img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>          
</body>
</html>

IMO, this approach is perfect for small sized images like <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" alt="thumbnail" height="200">. Otherwise using direct url of the image will be fine in src attribute eg:- <img src="uri-of-image/profile-pic.jpg" width="600" alt="No Profie Pic" height="600">

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文