본문 바로가기

Backend/Java

자바 썸네일 이미지 생성 (Thumbnail Image)

자바로 썸네일(thumbnail) 이미지를 만들어볼거에요.

 

원본 비율 유지

String oPath = "C:/Temp/40f0594a-b3f6-4c0f-a0b2-3cebbaf0d74e.jpg"; // 원본 경로
File oFile = new File(oPath);

int index = oPath.lastIndexOf(".");
String ext = oPath.substring(index + 1); // 파일 확장자

String tPath = oFile.getParent() + File.separator + "t-" + oFile.getName(); // 썸네일저장 경로
File tFile = new File(tPath);

double ratio = 2; // 이미지 축소 비율

try {
	BufferedImage oImage = ImageIO.read(oFile); // 원본이미지
	int tWidth = (int) (oImage.getWidth() / ratio); // 생성할 썸네일이미지의 너비
	int tHeight = (int) (oImage.getHeight() / ratio); // 생성할 썸네일이미지의 높이
	
	BufferedImage tImage = new BufferedImage(tWidth, tHeight, BufferedImage.TYPE_3BYTE_BGR); // 썸네일이미지
	Graphics2D graphic = tImage.createGraphics();
	Image image = oImage.getScaledInstance(tWidth, tHeight, Image.SCALE_SMOOTH);
	graphic.drawImage(image, 0, 0, tWidth, tHeight, null);
	graphic.dispose(); // 리소스를 모두 해제

	ImageIO.write(tImage, ext, tFile);
} catch (IOException e) {
	e.printStackTrace();
}

 

위의 코드에서 double ratio 값으로 비율을 조정하면 되요.

이외 맘에 들지 않은 코드는 커스텀하시면 되구요.

테스트해볼게요.

 

원본 (500 x 333) 43.5KB

 

썸네일 (ratio = 1.5) 9.37KB

 

썸네일 (ratio = 2) 축소 6.51KB

 

고정너비, 고정높이

비율로 줄이지 않고 고정너비와 고정높이를 주어서 썸네일을 만들어볼게요.

위의 코드에서 tWidth와 tHeight 변수를 고정값으로 수정해주세요.

나머지 코드는 같아요.

 

int tWidth = 200; // 생성할 썸네일이미지의 너비
int tHeight = 200; // 생성할 썸네일이미지의 높이

 

썸네일 (200 x 200) 6.18KB