5

Is it possible to create a PNG image and output it straight to the browser as part of a JAX-RS resource?

Something like this:

@Path("img/{externalId}")
@Stateless
@Produces({"image/png"})
public class MyImgResource {

  @GET
  public Response (@PathParam("externalId") String externalId) {
    // create image, write to buffered output stream

    return Response.ok().entity(stream).build();
  }
}

Would this work? Do I have to take care of the correct headers (Content-Type), or is this done by the @Produces annotation? Can output an image as a Response? Can I build a Response from a stream?

Hank
  • 4,597
  • 5
  • 42
  • 84

1 Answers1

9

Take a look at http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e323:

 @GET
 @Path("/images/{image}")
 @Produces("image/*")
 public Response getImage(@PathParam("image") String image) {
     File f = new File(image);

     if (!f.exists()) {
         throw new WebApplicationException(404);
     }

     String mt = new MimetypesFileTypeMap().getContentType(f);
     return Response.ok(f, mt).build();
 }
dweomer
  • 108
  • 6
  • 1
    Thx. I managed to do it similarly by creating the Image to a ByteOutputStream and building the Response from that. – Hank Apr 20 '11 at 22:41
  • 3
    Alternatively, you can just return any implementation of InputStream from your resource method and your JAX-RS implementation should be able to take it from there. – dweomer Apr 20 '11 at 22:50
  • 2
    @Hank, reading the image in advance as a ByteArray is a waste of memory. For large images, that would incur memory management woes. It's always better to return an InputStream and let the container worry about transferring the stream to the caller. – Isaac Mar 13 '14 at 15:02
  • @Isaac, absolutely, I couldn't agree more (with a bit more experience under my belt now). – Hank Mar 14 '14 at 08:12
  • @Isaac Do you mean something like this? `return new BufferedInputStream(new FileInputStream("source.png"));` – Socrates Jan 10 '19 at 00:28
  • 1
    @Socrates indeed. – Isaac Jan 10 '19 at 09:02