Reputation: 12858
I need to return an Image (as Stream) in one of my applications. After a short google i found a simple solution, but it only works for Opera and Chrome. Firefox and Safari will show a simple text with the info that the response is a stream.
Here's how i do it right now:
@GET
@Path("/getImage")
@Produces({
"images/gif", "images/png", "images/jpg", MediaType.APPLICATION_JSON
})
public Response getImage(@QueryParam("width") Integer width, @QueryParam("height") Integer height) {
//SOME UNRELEVANT STUFF...
String mmcpath = gi.filepath;
BufferedImage image = ImageUtil.getImageFromPath(mmcpath);
if (image != null) {
// resize the image to fit the GUI's image frame
image = ImageUtil.resize(image, width, height);
InputStream is = ImageUtil.getStreamFromImage(image, FileHelper.getFileSuffix(mmcpath));
if (is != null) {
return Response.ok(is).build();
} else {
return Response.noContent().build();
}
}
return Response.noContent().build();
}
I hope someone has an idea how i have to change this method to get it working with the other browsers too.
Thanks
Upvotes: 1
Views: 4813
Reputation: 12858
I did some more research and was able to fix my issue. (Note: I think this isn't 100% jersey)
First you have to define following two vars in your controller:
@Context
HttpHeaders header;
@Context
HttpServletResponse response;
After that you can handle the image-return with following code snippet:
//The mmcpath is the path to the image
BufferedImage image = ImageUtil.getImageFromPath(mmcpath);
if (image != null) {
image = ImageUtil.resize(image, width, height);
response.setContentType("images/jpg");
response.setHeader("Content-Type", FileHelper.getNameFromPath(mmcpath));
response.setHeader("Content-Disposition", "inline; filename=\"" + FileHelper.getNameFromPath(mmcpath) + "\"");
OutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.close();
return Response.ok().build();
}
And here's the code i use in my ImageUtil.getImageFromPath(mmcpath); Just to complete the whole stuff.
ImageIO.read(new File(path))
I hope someone else can use these snippets too!
Upvotes: 2