728x90
1.thumbnailator 의존성추가
자바에서 이미지 리사이징을 매우 간단하고 효율적으로 처리할 수 있게 도와주는 오픈소스 라이브러리를 추가해준다.
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>
2.이미지 리사이징
Thumbnails를 사용하여 높이는 자동으로 하고 너비는 800px로 리사이징하는 코드를 쉽게 만들수있다.
// 리사이징 처리 너비 800px
Thumbnails.of(originalImage)
.size(800, Integer.MAX_VALUE)
.outputFormat(extension)
.toFile(new File(filePath));
public class ImageUploadService {
private static final String UPLOAD_DIR = "C:/uploads/";
public String uploadImage(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
throw new IOException("Image file is empty");
}
try {
Files.createDirectories(Paths.get(UPLOAD_DIR));
String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new IOException("Invalid file name");
}
String extension = getFileExtension(originalFileName);
String fileName = System.currentTimeMillis() + "." + extension;
String filePath = UPLOAD_DIR + fileName;
// 원본 이미지를 BufferedImage로 읽기
BufferedImage originalImage = ImageIO.read(file.getInputStream());
if (originalImage == null) {
throw new IOException("Failed to read image content");
}
// 리사이징 처리 너비 800px
Thumbnails.of(originalImage)
.size(800, Integer.MAX_VALUE)
.outputFormat(extension)
.toFile(new File(filePath));
return "/images/" + fileName;
} catch (IOException e) {
log.error("File upload failed", e);
throw new IOException("Image Upload Fail", e);
}
}
private String getFileExtension(String fileName) {
int index = fileName.lastIndexOf('.');
if (index > 0) {
return fileName.substring(index + 1).toLowerCase(); // 확장자를 소문자로 통일
}
return "jpg"; // 기본 확장자
}
}
728x90