How to return a PNG image from Jersey REST service method to the browser

前端 未结 4 1899
粉色の甜心
粉色の甜心 2020-11-30 19:46

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

4条回答
  •  星月不相逢
    2020-11-30 19:58

    If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

    @Produces({ "image/png", "image/jpg" })
    @Provider
    public class BufferedImageBodyWriter implements MessageBodyWriter  {
      @Override
      public boolean isWriteable(Class type, Type type1, Annotation[] antns, MediaType mt) {
        return type == BufferedImage.class;
      }
    
      @Override
      public long getSize(BufferedImage t, Class type, Type type1, Annotation[] antns, MediaType mt) {
        return -1; // not used in JAX-RS 2
      }
    
      @Override
      public void writeTo(BufferedImage image, Class type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap mm, OutputStream out) throws IOException, WebApplicationException {
        ImageIO.write(image, mt.getSubtype(), out);
      } 
    }
    

    This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

    Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

    @Path("/whatever")
    @Produces({"image/png", "image/jpg"})
    public Response getFullImage(...) {
      BufferedImage image = ...;
      return Response.ok(image).build();
    }
    

    A couple of advantages to this approach:

    • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
    • It supports both png and jpg output (depending on the media types allowed by the resource method)

提交回复
热议问题