Returning An Image In REST API (Java 8, Spring, Swagger)

If you need to return an image file in a response one of your REST API, you can do this with following these steps:

  • read the image file
  • convert to byte array
  • encode to Base64
  • return encoded value as String

import io.swagger.api.ImagesApi;
import io.swagger.model.GetImagesResponse;
import io.swagger.model.Image;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ImageController implements ImagesApi {
@Override
public ResponseEntity<GetImagesResponse> getImages() {
try {
final GetImagesResponse response = new GetImagesResponse();
final InputStream inputStream = new ClassPathResource("images/bojack.jpg").getInputStream();
final byte[] bytes = IOUtils.toByteArray(inputStream);
final String encodedImage = Base64.getEncoder().encodeToString(bytes);
final Image image = new Image();
image.setValue(encodedImage);
response.add(image);
return new ResponseEntity<GetImagesResponse>(response, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("oops!");
}
}
view raw ImageController.java hosted with ❤ by GitHub

filetree

Full code:
https://github.com/afsinka/spring-boot_swagger_rest_image_base64

You can decode and test your Base64 value with:
https://codebeautify.org/base64-to-image-converter

Resources:
[0] https://www.baeldung.com/spring-controller-return-image-file
[1] https://www.baeldung.com/convert-input-stream-to-array-of-bytes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: