1

I have simple JAX-RS server application:

@GET
@Path("/getImage/{key}")
@Produces("image/jpeg")
public final BufferedImage getImageResource(@PathParam("key") String key) {
  final File file = new File(key); // the key will be "cat.jpeg" e.t.c.

  final BufferedImage image = ImageIO.read(new FileInputStream(file));

  return image;
}

After deploying war file to tomcat server (6.0), i do next:

http://localhost:8080/resource-service/getImage/cat.png

Problems:

1)On new File(key) it'll go to tomcat root directory. I'd like to have something like default root folder for resources inside project directory around classes.

2)Returning BufferedImage doesn't allowed as i understand, i get 500 error message:

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

I'd appreciate any advice, links. Thanks in advance!

Serg
  • 85
  • 1
  • 1
  • 7
  • You didn't mention your JAX-RS provider, but in any case none of them (afaik) provides a MessageBodyWriter out of the box capable of serializing a BufferedImage directly. Please see my answer [here](http://stackoverflow.com/a/9204824/680925) for information on converting the buffered image into a byte array or input stream as an intermediary step before serialization - http://stackoverflow.com/a/9204824/680925. – Perception Dec 12 '12 at 17:13

1 Answers1

1

In order to get access to the files in your WAR package you should use ServletContext. First, inject it first into your class as a variable:

@Context
ServletContext context;

and then find files using:

final File file = new File(this.context.getRealPath(key));

It's not possible to return a BufferedImage (and map it automatically to image/jpeg), but in your example you don't need to do it. Just return a JAX-RS response:

@GET
@Path("/getImage/{key}")
@Produces("image/jpeg")
public final Response get(@PathParam("key") String key) {
    return Response.ok()
        .entity(this.context.getResourceAsStream(key))
        .type("image/jpeg")
        .build();
}

Similar question: Dynamically create image from JAX-RS servlet

Community
  • 1
  • 1
yegor256
  • 102,010
  • 123
  • 446
  • 597