0

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.

Harish
  • 46
  • 4

0 Answers0