简体   繁体   English

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

[英]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}当我点击localhost:8080:/getImage/app/path={imagePath}这样的 API 时,我想要一张图片

While I hit this API it will return me an Image.当我点击这个 API 时,它会返回一个图像。

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?有什么方法可以在点击 java 中的任何 URL 时返回图像?

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

You can use IOUtils .您可以使用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();
    }
}

Just return a file object with correct HTTP-Headers ( Content-Type and Content-Disposition ) will work in most cases/environments.在大多数情况/环境下,只需返回具有正确 HTTP 标头( Content-TypeContent-Disposition )的文件对象即可。

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:也可以看看:

I want to an image while I hit an API like localhost:8080:/getImage/app/path={imagePath}当我按下localhost:8080:/getImage/app/path={imagePath}这样的API时,我想拍摄一张图片localhost:8080:/getImage/app/path={imagePath}

While I hit this API it will return me an Image.当我点击此API时,它将返回我一张图片。

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?有什么方法可以在击中Java中的任何URL时返回图像?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Spring REST中的图像返回到浏览器 - How to return image in Spring REST to browser 如何让Java rest api调用立即返回不等? - How to make Java rest api call return immediately not wait? Java Spring:在rest api中返回大字符串 - Java Spring : Return large string in rest api 如何从MySQL获取Malayalalam语言的数据并通过Java Rest API在浏览器中显示数据 - How to fetch data in Malayalalam language from MySQL and display it in browser via Java Rest API How to add multiple references of model in java REST API of return type arrayList? - How to add multiple references of model in java REST API of return type arrayList? 如何使 Java Rest API 在处理前半部分后返回响应,然后在返回响应后继续后半部分? - How to make Java Rest API to return response after first half of processing, then continue the second half after return response? Java Spring rest api中多对一关系的返回id - Return id of Many-To-One relation in Java Spring rest api Rest API curl 命令不返回值(java Spring) - Rest API curl command does not return values (java Spring) 如何在java中缓存REST API响应 - How to cache REST API response in java 如何使用Spring Boot应用程序从Rest API返回HTML - How to return html from Rest API with spring boot application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM