[JAVA] 이미지파일 사이즈 변경 및 확인.

[JAVA] 이미지파일 사이즈 변경 및 확인.

반응형

상황 예시)

모바일 카메라로 사진을 촬영 한다.

각 디바이스 마다 width , height 가 다르게 찍히게 될테니 ,

이를 크기 고정시키고 웹에 다시 업로드 시키고자 한다.

이럴때 필요한 리사이징 & 변경된 크기 확인을 하기 위한 용도이다.

try {

// ex) 모바일 세로 고정 크기 235 * 510

// ex) 모바일 가로 고정 크기 510 * 235

// 원본

image = ImageIO.read( new File( "이미지 풀 경로" ));

// 원본 width , height

int ori_width = image.getWidth(null);

int ori_height = image.getHeight(null);

int r_w = 235 ; // 리사이징 될 width

int r_h = 510 ; // 리아시징 될 height

if (ori_width > ori_height) { // 가로

r_w = 510 ;

r_h = 235 ;

}

// 리사이징

Image resizing = image.getScaledInstance(r_w , r_h , Image.SALE_SMOOTH);

BufferedImage newImage = new BufferedImage(r_w , r_h , BufferedImage.TYPE_INT_RGB);

Graphics g = newImage.getGraphics();

g.drawImage(resizing, 0 , 0 , null);

g.dispose();

ImageIO.write(newImage, "jpg" , new File( "생성할풀경로" ));

} catch (Exception e) {

e.printStackTrace();

}

File imageFile = new File( "생성한풀경로" );

// 변경된 사이즈 확인.

if (imageFile.exists()) {

BufferedImage bi = ImageIO.read( new File( "생성한풀경로" ));

System.out.println( "변경된 width : " + bi.getWidth());

System.out.println( "변경된 height : " + bi.getHeight());

from http://code-zzolbo.tistory.com/55 by ccl(A) rewrite - 2021-12-21 11:27:39