How to return an Image to browser in rest API in JAVA?
Asked Answered
D

3

7

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?

Donielle answered 18/3, 2018 at 10:28 Comment(1)
Store the image as base64 encoded string and return that string. I can provide a sample code if neededEldwun
D
2

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();
    }
}
Douville answered 19/3, 2018 at 4:42 Comment(0)
R
2

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();
}
Ricardo answered 18/3, 2018 at 10:50 Comment(3)
Hi, You are returning inputstream in this method is returning byte[] array. It is giving error. and should I have to add something in pom.xml or any file?Donielle
You were right i told you i dont have the enviroment in this machine, however i have updated the answer please checkRicardo
even better if you directly returned os.toByteArray()Electrokinetic
D
2

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();
    }
}
Douville answered 19/3, 2018 at 4:42 Comment(0)
V
1

Just return a file object with correct HTTP-Headers (Content-Type and Content-Disposition) will work in most cases/environments.

Pseudocode

File result = createSomeJPEG(); 
/*
 e.g.
 RenderedImage rendImage = bufferedImage;
 File file = new File("filename.jpg");
 ImageIO.write(rendImage, "jpg", file);
*/
response().setHeader("Content-Disposition", "attachment;filename=filename.jpg;");
response().setHeader("Content-Type", "image/jpeg");
return ok(result);

See also:

Vostok answered 18/3, 2018 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.