如何将API字符串响应保存到Java中的图像文件?
我正在尝试保存包含图像作为二进制字符串的二进制字符串的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论