java 如何使用 HTML 标签向 JSP 页面显示以字节为单位的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/943729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:29:48  来源:igfitidea点击:

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

javahtmljspimage

提问by Andreas Petersson

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

我有 ByteArrayOutputStream,它包含一个以字节为单位的 JPEG 图像。我的要求是在JSP页面中显示该图像(使用 HTML 标签在前端显示图像)。我怎么做?

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

我已经提到了这BufferedImage门课,但这对我来说很困惑,因为我是新手。

回答by Andreas Petersson

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

如果图像不是太大,您可以按如下方式进行。

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

Where iVBORw0KGgoAAAANS... is the Base64encoded bytes.

其中iVBORw0KGgoAAAANS... 是Base64编码的字节。

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

Base64 编码可以使用库完成,例如Ostermiller Java Utilities 的Base64 Java 库org.apache.commons.codec.binary.Base64

回答by Jon Skeet

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 imgtag which includes enough information to let you respond to the subsequent request for the image with the data in your ByteArrayOutputStream.

除非您使用“数据”URI(对小图像有用),否则浏览器将发出两个请求:一个请求 HTML,另一个请求图像。您需要能够输出一个img包含足够信息的标签,以便您可以使用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.

根据您获取该 JPEG 文件的方式以及您的服务器的扩展方式,这可能涉及将图像写入磁盘、将其缓存在内存中、重新生成它,或这些的任意组合。

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.

如果您可以延迟图像生成,直到浏览器首先请求实际图像,那是非常理想的。这可能涉及在图像的 URL 中添加额外的参数 - 例如图形上的点,或要生成的缩略图的大小,或者无论您的图像是什么。

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.

如果您不熟悉 JSP 和 HTML,我强烈建议您首先关注 HTML 方面。在确定如何动态提供服务之前,先确定您需要提供什么以及浏览器将执行什么操作。从 HTML 和图像的静态页面和文件开始,然后研究如何生成它们。