如何在JAVA中的rest API中将图像返回到浏览器?

时间:2018-03-18 10:28:25

标签: java spring restful-url java-api

我想点击像localhost:8080:/getImage/app/path={imagePath}

这样的API时的图片

当我点击此API时,它会返回一个Image。

这可能吗?

实际上,我试过这个,但它给了我一个错误。 这是我的代码,

@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;
}

我的错误,

java.io.IOException: The image-based media type image/webp is not supported for writing

有没有办法在点击java中的任何URL时返回Image?

4 个答案:

答案 0 :(得分:2)

我没有测试它,因为我没有这台机器的环境,但从逻辑上讲它应该像下面这样工作,把它作为输入流读取,让你的方法返回@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);
}

<强>更新 取决于@Habooltak Ana的建议,不需要创建输入流,代码应该如下所示

@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();
}

答案 1 :(得分:2)

您可以使用IOUtils。这是代码示例。

@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();
    }
}

答案 2 :(得分:1)

只需返回一个带有正确HTTP标头的文件对象(Content-TypeContent-Disposition)就可以在大多数情况下/环境中使用。

伪代码

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);

另见:

答案 3 :(得分:0)

这是一个简单的解决方案:

@GET
@Path("/somePath")
public void getImage(@Context HttpServletResponse res) throws IOException {
    java.nio.file.Path path = Paths.get("filePath");
    res.getOutputStream().write(Files.readAllBytes(path));
    res.getOutputStream().flush();
}