본문 바로가기

Spring Boot

[SpringBoot]Spring Boot 환경에서 이미지 크기 조정

반응형

Thumbnailator 라이브러리를 사용하여 Spring Boot 환경에서 이미지 크기 조정을 구현하는 방법입니다.

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/image")
public class ImageController {

    @PostMapping("/resize")
    public ResponseEntity<byte[]> resizeImage(@RequestParam("image") MultipartFile image,
                                              @RequestParam("width") int width,
                                              @RequestParam("height") int height) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Thumbnails.of(image.getInputStream())
                .size(width, height)
                .toOutputStream(outputStream);
        return new ResponseEntity<>(outputStream.toByteArray(), HttpStatus.OK);
    }
}

 

이미지 파일과 크기가 조정된 이미지의 원하는 너비 및 높이를 사용하여 /image/resize  POST 요청을 수행합니다. 축소판 그림 라이브러리는 이미지 크기를 조정하는 데 사용되며 크기가 조정된 이미지는 200 OK 상태의 응답 엔터티로 반환됩니다.

사용자 환경에 섬네일레이터가 설치되어 있다고 가정합니다. Maven을 사용하는 경우 pom.xml 파일에 다음과 같은 종속성을 추가하여 섬네일레이터를 설치할 수 있습니다.

<dependency>
  <groupId>net.coobird</groupId>
  <artifactId>thumbnailator</artifactId>
  <version>0.4.11</version>
</dependency>
반응형