Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw image in RESTeasy

I have this service with RESTeasy:

@GET
@Path("/{name}")
@Produces("image/jpeg")
public BufferedImage get(@PathParam("name") String name) {

    Monitor m = Monitor.getMonitor(name);

    if (m == null) {
        return null;
    }

    return m.getImage();
}

then I get after request

Could not find MessageBodyWriter for response object of type: java.awt.image.BufferedImage of media type: image/jpeg

Is there any "direct way" to get the image into the response ?


Thanks to @Robert for directions. Here working code:

@GET
@Path("/{name}")
@Produces("image/jpeg")
public byte[] get(@PathParam("name") String name) {

    Monitor m = Monitor.getMonitor(name);

    if (m == null) {
        return null;
    }

    ByteArrayOutputStream bo = new ByteArrayOutputStream(2048);
    try {
        ImageIO.write(m.getImage(),"jpeg",bo);
    } catch (IOException ex) {
        return null;
    }

    return bo.toByteArray();
}
like image 679
PeterMmm Avatar asked Apr 15 '12 15:04

PeterMmm


1 Answers

You should try to

  • encode the BufferedImage as JPG. Take a look at class javax.imageio.ImageIO
  • declare your method to return a byte[]
  • make sure that your application will always run on a server that is not started with java.awt.headless=true (i.e. no graphics subsystem)

Please let us know if that works, cause I have no idea if it will and can't try it myself right now.

like image 151
Robert Petermeier Avatar answered Sep 20 '22 13:09

Robert Petermeier