如何将 PNG 图像从 Jersey REST 服务方法返回到浏览器 [英] How to return a PNG image from Jersey REST service method to the browser

查看:39
本文介绍了如何将 PNG 图像从 Jersey REST 服务方法返回到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行 Jersey REST 资源的网络服务器,我想知道如何获取浏览器 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.

话虽如此,如果您决定确实需要从网络服务传输图像数据,您可以使用以下(伪)代码来实现:

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();
}

添加异常处理等

这篇关于如何将 PNG 图像从 Jersey REST 服务方法返回到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆