users@jersey.java.net

Re: [Jersey] Streaming a BufferedImage

From: Casper Bang <casper.bang_at_gmail.com>
Date: Wed, 16 Dec 2009 02:53:25 +0100

cgswtsu78 wrote:
> Hello,
>
> I'm new to Jersey and restful web services in general. Is there a way to
> stream a BufferedImage to the browser using an HTTP GET request? Basically,
> I type in a URL http://localhost:8080/jersey/getImage and the browser
> displays the BufferedImage returned from the method mapped to the "getImage"
> path. A simple example would be quite helpful. Appreciate the help!
>

Technically, what you are asking for is something like this:

@GET
@Path("/getImage")
public byte[] getImage(){
    final Image image = ...
    return ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
}

However, that probably won't get you very far. You probably want to
return an image using some common format like jpg or png, in which case
you could use ImageIO:

@GET
@Path("/getImage")
@Produces("image/png")
public StreamingOutput getImage() throws IOException{
    final Image image = ...
       
    return new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException,
WebApplicationException {
            ImageIO.write(image, "png", output);
        }
    };
}

That's what I do anyway, if there's a smarter way I am sure people will
let us know. :)

Cheers,
Casper