사용자가 업로드 한 로고이미지를 리사이징한 후 S3 버킷에 저장해야하는 로직을 구현할 일이 있었다.
아래는 이미지를 컨트롤러에서 받아 리사이징 하는 코드이다.
Using Java Library
public class ImageUtils {
public static File multipartFileToFile(MultipartFile multipartFile) throws IOException {
File file = new File(multipartFile.getOriginalFilename());
multipartFile.transferTo(file);
return file;
}
public static BufferedImage resizeImage(MultipartFile image, int maxWidth, int maxHeight) throws Exception{
int convertedWidth = 0;
int convertedHeight = 0;
float maxRatio = maxHeight / (float)maxWidth;
String ext = FilenameUtils.getExtension(image.getOriginalFilename());
// MultipartFile to BufferedImage
File inputFile = ImageUtils.multipartFileToFile(image);
BufferedImage inputImage = ImageIO.read(inputFile);
// current width & height
int width = inputImage.getWidth();
int height = inputImage.getHeight();
float ratio = height / (float)width;
// decide to convert or not
if(width > maxWidth || height > maxHeight) {
if(ratio < maxRatio) {
convertedWidth = (int)(width * (maxWidth / (float)width));
convertedHeight = (int)(height * (maxWidth / (float)width));
}else{
convertedWidth = (int)(width * (maxHeight / (float)height));
convertedHeight = (int)(height * (maxHeight / (float)height));
}
}else{
return inputImage;
}
Image srcImg;
if(ext.equals("bmp") || ext.equals("png") || ext.equals("gif")){
srcImg = ImageIO.read(inputFile);
}else{
srcImg = new ImageIcon(inputFile.toURL()).getImage();
}
Image imgTarget = srcImg.getScaledInstance(convertedWidth, convertedHeight, Image.SCALE_SMOOTH);
int pixels[] = new int[convertedWidth * convertedHeight];
PixelGrabber pg = new PixelGrabber(imgTarget, 0, 0, convertedWidth, convertedHeight, pixels, 0, convertedWidth);
pg.grabPixels();
BufferedImage outputImage = new BufferedImage(convertedWidth, convertedHeight, inputImage.getType());
outputImage.setRGB(0, 0, convertedWidth, convertedHeight, pixels, 0, convertedWidth);
return outputImage;
}
}
Using Scalr Library
public static BufferedImage resizeImageByScalr(MultipartFile image, int maxWidth, int maxHeight) throws IOException {
BufferedImage orgImg = ImageIO.read(image.getInputStream());
return Scalr.resize(orgImg, Scalr.Method.AUTOMATIC, Mode.AUTOMATIC, maxWidth, maxHeight);
}
Reference