如何从 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();
}
添加异常处理等
相关文章