I want to an image while I hit an API like localhost:8080:/getImage/app/path={imagePath}
While I hit this API it will return me an Image.
Is this possible?
Actually, I have tried this but it is giving me an ERROR. Here is my code,
@GET
@Path("/app")
public BufferedImage getFullImage(@Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
return resizeImage(300, 300, objectKey);
}
public static BufferedImage resizeImage(int width, int height, String imagePath)
throws MalformedURLException, IOException {
BufferedImage bufferedImage = ImageIO.read(new URL(imagePath));
final Graphics2D graphics2D = bufferedImage.createGraphics();
graphics2D.setComposite(AlphaComposite.Src);
// below three lines are for RenderingHints for better image quality at cost of
// higher processing time
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(bufferedImage, 0, 0, width, height, null);
graphics2D.dispose();
System.out.println(bufferedImage.getWidth());
return bufferedImage;
}
My ERROR,
java.io.IOException: The image-based media type image/webp is not supported for writing
Is there any way to return an Image while hitting any URL 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();
}