스마트웹앱콘텐츠전문가/JAVA

[파일업로드]ImageIO를 이용하여 이미지 파일 크기 줄여서 저장하기

9D4U 2017. 9. 12. 13:29
728x90
반응형

필요한 것.

- import javax.imageio.ImageIO;

- import java.awt.Graphics2D;

- import java.awt.image.BufferedImage;


예시)


try{

String OriginalFileName = uploadfile.getOriginalFilename(); //uploadfile 형식은 MultipartFile

//썹네일 가로 사이즈

int thumnail_width = 300;

//썸네일 세로 사이즈

int thumnail_height = 300;

//MultipartFile to File

File f = multipartToFile(uploadfile);

//생성할 썸네일파일의 경로, 로컬 저장

File thumb_file_name = new File(attach_path + uploadFilename);

File thumb_file = thumb_file_name.getAbsoluteFile();

//이미지 사이즈 줄이기 시작

BufferedImage buffer_original_image = ImageIO.read(f);

BufferedImage buffer_thumnail_image = new BufferedImage(thumnail_width, thumnail_height,                         BufferedImage.TYPE_3BYTE_BGR);

Graphics2D graphic = buffer_thumnail_image.createGraphics();

graphic.drawImage(buffer_original_image, 0, 0, thumnail_width, thumnail_height, null);

//이미지 사이즈 줄이기 끝

 //사이즈가 줄여진 이미지를 로컬 경로에 저장

ImageIO.write(buffer_thumnail_image, "jpg", thumb_file_name);

/*썸네일 파일 유무 조건 처리*/

if(thumb_file_name.exists()){

long filesize = thumb_file_name.length();

if(filesize > 0) {

try {

} catch(Exception e) {

resultMap.put("errorMessage", e.getMessage());

}

}

}else{

/*파일이 생성되지 않았으면~~*/

}

}catch(Exception e){

e.printStackTrace();

}

728x90