如何将API字符串响应保存到Java中的图像文件?

发布于 2025-02-06 20:23:33 字数 1392 浏览 5 评论 0原文

我正在尝试保存包含图像作为二进制字符串的二进制字符串的API响应。 Azure DevOps工作项目API允许在工作项目中创建和添加附件。我可以创建一个附件,并在Postman中以 JPG 文件获取附件。但是,当我尝试在代码中执行此操作时,我将响应作为字符串获得,但将其保存到文件中会失败。

// Using a library
var webApi = new AzDClientApi("organizationName", "projectName", "personalAccessToken");
var wit = webApi.getWorkItemTrackingApi();
String res = wit.getAttachment("attachment-id-here", "image.jpg")

// Method 1) This didn't work
FileWriter writer = new FileWriter("image.jpg");
writer.write(res); // This gave me an image of 72 KB whereas the original file size is 41 KB.

// Method 2) Resulted in error as ImageIO.read() couldn't read the image stream.
InputStream stream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));
BufferedImage image = ImageIO.read(stream);
ImageIO.write(image, "jpg", new File("image.jpg"));

// Error
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
    at java.desktop/javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at java.desktop/javax.imageio.ImageIO.getWriter(ImageIO.java:1608)
    at java.desktop/javax.imageio.ImageIO.write(ImageIO.java:1540)
    at Main.main(Main.java:44)

我尝试如帖子在这里,但这不行。

I'm trying to save the API response that contains image as a binary string to a file in java. Azure DevOps work items API allows to create and add attachments to the work items. I can create an attachment and get the attachment as jpg file in Postman. However, When I tried to do that in code I'm getting the response as a string but saving it to a file fails.

// Using a library
var webApi = new AzDClientApi("organizationName", "projectName", "personalAccessToken");
var wit = webApi.getWorkItemTrackingApi();
String res = wit.getAttachment("attachment-id-here", "image.jpg")

// Method 1) This didn't work
FileWriter writer = new FileWriter("image.jpg");
writer.write(res); // This gave me an image of 72 KB whereas the original file size is 41 KB.

// Method 2) Resulted in error as ImageIO.read() couldn't read the image stream.
InputStream stream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));
BufferedImage image = ImageIO.read(stream);
ImageIO.write(image, "jpg", new File("image.jpg"));

// Error
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
    at java.desktop/javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at java.desktop/javax.imageio.ImageIO.getWriter(ImageIO.java:1608)
    at java.desktop/javax.imageio.ImageIO.write(ImageIO.java:1540)
    at Main.main(Main.java:44)

I tried as shown in the post here but that didn't work too.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文