Skip to content

Instantly share code, notes, and snippets.

@jsfeng
Created April 5, 2012 18:10
Show Gist options
  • Save jsfeng/2312925 to your computer and use it in GitHub Desktop.
Save jsfeng/2312925 to your computer and use it in GitHub Desktop.
Streaming images in JAX-RS REST service.
@Produces("image/jpeg")
@Path("/images")
public class ImageRestServiceImpl {
@Path("{id}")
public StreamingOutput getImage(@PathParam("id") int id) {
BufferedImage image = generateImage(id); //generate image using
return new StreamingImageOutput(image);
}
}
class StreamingImageOutput implements StreamingOutput {
private BufferedImage image;
public StreamingImageOutput(BufferedImage image) {
this.image = image;
}
public void write(OutputStream output) throws IOException, WebApplicationException {
JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(output);
JPEGEncodeParam enParam = jencoder.getDefaultJPEGEncodeParam(image);
enParam.setQuality(1.0F, true);
jencoder.setJPEGEncodeParam(enParam);
jencoder.encode(image);
output.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment