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.util.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
public class ImageController implements ImagesApi {
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();
return new ResponseEntity<GetImagesResponse>(response, HttpStatus.OK);
} catch (Exception e) {
throw new RuntimeException("oops!");


Full code:

You can decode and test your Base64 value with:


Leave a Reply

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

You are commenting using your 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: