03.08 multipart 이미지 파일 리사이징 해서 파일 만들기
2023. 3. 8. 00:29ㆍ개발일지
public File resizeImage(MultipartFile file, int targetWidth, int targetHeight) throws IOException {
//1. MltipartFile 에서 BufferedImage로 변환
BufferedImage originalImage = ImageIO.read(file.getInputStream());
//2. Graphics2D 로 리사이징
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
//3. BufferedImage 로 File 생성
File outputfile = new File(file.getOriginalFilename());
try {
if (outputfile.createNewFile()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String type = file.getContentType().substring(file.getContentType().indexOf("/")+1);
ImageIO.write(resizedImage, type, bos);
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
Files.copy(inputStream, outputfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return outputfile;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return null;
}
1. MltipartFile 에서 BufferedImage로 변환
BufferedImage originalImage = ImageIO.read(file.getInputStream());
2. Graphics2D 로 리사이징
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
3. BufferedImage 로 File 생성
File outputfile = new File(file.getOriginalFilename());
if (outputfile.createNewFile()) { //신규파일 생성
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String type = file.getContentType().substring(file.getContentType().indexOf("/")+1); //확장자 확인
ImageIO.write(resizedImage, type, bos);
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
Files.copy(inputStream, outputfile.toPath(), StandardCopyOption.REPLACE_EXISTING); //파일 덮어쓰기
return outputfile;
}
'개발일지' 카테고리의 다른 글
03.17 QueryDSL 기본문법 (0) | 2023.03.17 |
---|---|
Nginx와 Let's Encrypt로 HTTPS 웹 서비스 배포하기 (feat. Certbot) (0) | 2023.03.16 |
03.07 JPA Pagination을 이용한 무한 스크롤 구현기 (0) | 2023.03.06 |
03.06 TIL (0) | 2023.03.06 |
03.06 Refresh Token (양식) (0) | 2023.03.06 |