How to return a PNG image from Jersey REST service method to the browser(如何从 Jersey REST 服务方法返回 PNG 图像到浏览器)
问题描述
我有一个运行 Jersey REST 资源的 Web 服务器,我想知道如何获取浏览器 img 标签的图像/png 参考;在提交表单或获得 Ajax 响应之后.添加图形的图像处理代码正在工作,只需要以某种方式返回即可.
I have a web server running with Jersey REST resources up and I wonder how to get an image/png reference for the browsers img tag; after submitting a Form or getting an Ajax response. The image processing code for adding graphics is working, just need to return it somehow.
代码:
@POST
@Path("{fullsize}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("image/png")
// Would need to replace void
public void getFullImage(@FormDataParam("photo") InputStream imageIS,
@FormDataParam("submit") String extra) {
BufferedImage image = ImageIO.read(imageIS);
// .... image processing
//.... image processing
return ImageIO. .. ?
}
干杯
推荐答案
我不相信在 REST 服务中返回图像数据是个好主意.它占用了应用服务器的内存和 IO 带宽.最好将该任务委托给针对这种传输进行了优化的适当 Web 服务器.您可以通过向图像资源发送重定向来完成此操作(作为带有图像 URI 的 HTTP 302 响应).这当然假设您的图像被安排为网络内容.
I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.
话虽如此,如果您决定确实需要从 Web 服务传输图像数据,您可以使用以下(伪)代码来完成:
Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:
@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {
BufferedImage image = ...;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
// uncomment line below to send non-streamed
// return Response.ok(imageData).build();
// uncomment line below to send streamed
// return Response.ok(new ByteArrayInputStream(imageData)).build();
}
添加异常处理等
这篇关于如何从 Jersey REST 服务方法返回 PNG 图像到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 Jersey REST 服务方法返回 PNG 图像到浏览器


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01