javaspringspring-bootpostmanjpeg

Spring Boot: Visualize image on Postman


I have this endpoint:

@GetMapping("/thumbnail/{imageName}")
@PreAuthorize("hasRole('BASIC')")
public ResponseEntity<InputStreamResource> natalChartThumbnail() throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    // 🔹 Generate thumbnail
    BufferedImage bufferedImage = Thumbnails.of(new File("/usr/local/bin/tmp/scaled_sun_in_cancer_moon_in_aquarius.jpg"))
            .scale(1.0)
            .asBufferedImage();

    ImageIO.write(bufferedImage, "jpg", os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("image/jpg"))
            .body(new InputStreamResource(is));

}

But in Postman, I see this:

enter image description here

and imageExtension: jpg

I also tried with:

 return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("image/jpeg"))
                .body(new InputStreamResource(is));

with the same result


Solution

  • I found the issue. You didn't try this option given below:

    produces = MediaType.IMAGE_JPEG_VALUE
    

    Please try the above option. I have cleaned up your code a little bit. So, modify your code based on the code given below:

    package com.example;
    
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.imageio.ImageIO;
    
    import org.springframework.core.io.InputStreamResource;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import net.coobird.thumbnailator.Thumbnails;
    
    @RestController
    public class SampleController {
        
        @GetMapping(value = "/thumbnail/{imageName}", produces = MediaType.IMAGE_JPEG_VALUE)
        public ResponseEntity<InputStreamResource> natalChartThumbnail(@PathVariable String imageName) throws IOException {
    
            ByteArrayOutputStream os = new ByteArrayOutputStream();
    
            // 🔹 Generate thumbnail
            BufferedImage bufferedImage = Thumbnails.of(new File("/Users/anisb/" + imageName + ".jpg"))
                    .scale(1.0)
                    .asBufferedImage();
    
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream in = new ByteArrayInputStream(os.toByteArray());
    
            return ResponseEntity.ok().body(new InputStreamResource(in));
    
        }
    }
    

    This works.

    Postman Screenshot:

    enter image description here