Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an Image to browser in rest API in JAVA?

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?

like image 604
Sharvil Avatar asked Mar 18 '18 10:03

Sharvil


People also ask

How do I view photos in spring boot?

We start Spring Boot application. We navigate to http://localhost:8080/sid to display the image in the browser. In this tutorial, we have shown how to send image data to the client from a Spring Boot applications.


1 Answers

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();
    }
}
like image 133
Nitin Avatar answered Sep 24 '22 14:09

Nitin