How to return an Image to browser in rest API in JAVA?
i didn't test it due to i don't have the environment in this machine, but logically it should work like the following, read it as input stream and let your method returns @ResponseBody byte[]
@GET
@Path("/app")
public @ResponseBody byte[] getFullImage(@Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return IOUtils.toByteArray(is);
}
UPDATE depending on @Habooltak Ana suggestion there is no need to create an input stream, the code should be look like the following
@GET
@Path("/app")
public @ResponseBody byte[] getFullImage(@Context UriInfo info) throws
MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
return os.toByteArray();
}
You can use IOUtils. Here is code sample.
@RequestMapping(path = "/getImage/app/path/{filePath}", method = RequestMethod.GET)
public void getImage(HttpServletResponse response, @PathVariable String filePath) throws IOException {
File file = new File(filePath);
if(file.exists()) {
String contentType = "application/octet-stream";
response.setContentType(contentType);
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
// copy from in to out
IOUtils.copy(in, out);
out.close();
in.close();
}else {
throw new FileNotFoundException();
}
}