-
[Java] multipartFile 이미지 리사이징 예제코드프로그래밍 언어/Java 2022. 11. 13. 16:27
사용자가 업로드 한 로고이미지를 리사이징한 후 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
[ Java ] 자바 - 저장된 이미지 파일 변환 후 사이즈 조정
변환할 확장자나 사이즈는 알맞게 수정하시면 됩니다. File file = new File(_파일경로_, _파일명_); File flTgt = new File(_생성경로_, _생성파일명_+".jpg"); boolean isConvert = ImageUtils.convertFmt(file, flTgt); if(isConver
aorica.tistory.com
728x90'프로그래밍 언어 > Java' 카테고리의 다른 글
[Java] Static Block 실행시점과 싱글톤(Singleton)에서의 활용 (0) 2022.12.28 [Java] 클래스 로드와 클래스 초기화 (StaticInnerClass, InnerClass, MemoryLeak) (0) 2022.11.06 [Java/Kotlin] Static nested class 와 Inner Class 중 무엇을 써야할까? (0) 2022.11.06 [Java] 바이트코드 조작하기 (JavaAgent, JVM, Jacoco) (0) 2022.06.06 [Java] JVM 이 무엇인지, 어떻게 작동하는지 대충 훑어보자! (feat. 클래스로더) (1) 2022.05.29