개발 공부

multipart 이미지 파일 리사이징 해서 파일 만들기 본문

자바, 스프링, 웹개발/웹개발

multipart 이미지 파일 리사이징 해서 파일 만들기

아이셩짱셩 2020. 12. 22. 12:52
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;
    
}

'자바, 스프링, 웹개발 > 웹개발' 카테고리의 다른 글

잡다한 기술  (0) 2021.01.06
html submit 꼼수 js에서 form 만들기  (0) 2020.12.28
타임리프(thymeleaf) java enum select option  (0) 2020.12.21
AJAX delete 파라미터  (0) 2020.12.21
AJAX 에러 처리  (0) 2020.12.21
Comments