Forum Discussion

cl509920's avatar
New Contributor
8 years ago

Groovy Script to store an image file as .jpg from http response body with content type as image/jpeg

An API GET response returns an image in the body, like this: This is not an attachment.

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Sat, 06 May 2017 15:32:05 GMT
Cache-Control: no-cache
Cache-Control: no-store
Cache-Control: max-age=0
X-Content-Type-Options: nosniff
X-XSS-Protection: 1
Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: image/jpeg
Content-Length: 12888 ÿØÿà JFIF ` ` ÿáÈExif MM * 2 J; ^GF GI ? ‡i f Æ2009:03:12 13:48:28 Corbis ? œ? °’‘ 17 ’’ 17 2008:02:11 11:32:43 2008:02:11 11:32:43 ( $ œ ` ` ÿØÿÛ C $.' ",#(7),01444'9=82<.342ÿÛ C 2!!2 ...... and so on.


Postman decodes the image an displays it, it is an animal in this case.

I have to store the response as an image file (.jpg) using a groovy script in soapUI(soapUI is used to test the API)

This is what I've tried in a Groovy Script step, but the image saved is unintelligible malformed.

def getImageResponse = new String(testRunner.testCase.testSteps["GET Image"].testRequest.response.responseContent);
byte[] imageInByte;
BufferedImage originalImage = ByteArrayInputStream(getImageResponse.getBytes()));

// convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
imageInByte = baos.toByteArray();

// convert byte array back to BufferedImage
InputStream inRead = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert =;

ImageIO.write(bImageFromConvert, "jpg", new File("C:\\animal.jpg"));

 I guess that what I am doing to save the image in .jpg is not correct. Can someone help?

Attach is the raw response.

Thanks in advance.

1 Reply

  • cl509920's avatar
    New Contributor
    0down voteaccept

    This is how I did this. From the Script Assertion of the http GET request. Hope It helps someone.

    def ins = context.httpResponse.getRawResponseBody();
    def isImageSaved = false;
    InputStream inputStream;
    FileOutputStream outputStream;
    if (ins){
        try {
            inputStream = new ByteArrayInputStream(ins);
            outputStream = new FileOutputStream(new File(context.expand("C:\\animal.jpg")));
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = != -1) {
                outputStream.write(bytes, 0, read);
            isImageSaved = true;
        }catch (Exception e){
            log.error e;
    } else {
        log.error "image does not exist...";
    context.testCase.setPropertyValue("isImageSaved", isImageSaved.inspect());