썸네일 처리 메서드(가로 < 세로)
Thumbnail 처리(가로 폭 < 세로 폭 [예]증명사진)
- 설명
길이가 너비보다 큰 경우의 썸네일 생성 메서드
전체적인 크기를 줄이고 가로 영역에 흰색 공백 처리!!!
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
public static boolean createThumbnailImageForMsn(String inputFile, String outputFile, int width, int height) throws FileNotFoundException, IOException{
BufferedImage sourceImage = ImageIO.read(new BufferedInputStream(new FileInputStream(inputFile)));
// height만 주고 width를 주지 않으면 height에 맞게 width scale이 자동조정됨
Image thumbnail = sourceImage.getScaledInstance(-1, height, Image.SCALE_SMOOTH);
BufferedImage bufferedThumbnail = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedThumbnail.getGraphics();
int thumbnailWidth = thumbnail.getWidth(null);
// 1. bufferedThumbnail의 Graphics에 이미지를 drawing한 후, 여백이 검은색으로 채워지는 문제가 있음.
// -> 남는 여백을 white로 채워야 함.
// -> 이미지 사이즈를 계산하여 가로축인 x position을 동적 계산해야 함.
// 세로 비율이 더 큰 경우 x position 계산
int xPosition = 0;
if ( thumbnailWidth < width ) {
xPosition = (int)(width-thumbnailWidth)/2;
}
g.setColor(Color.WHITE);
// BufferedImage에 축소된 이미지 drawing (이 때 x position은 가운데 위치하도록 함)
g.drawImage(thumbnail, xPosition, 0, thumbnail.getWidth(null), thumbnail.getHeight(null), Color.WHITE, null);
// 세로 비율이 더 큰 경우 남는 여백을 white로 채움
if ( thumbnailWidth < width ) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, xPosition, height);
g.fillRect(xPosition+thumbnailWidth, 0, (width-xPosition-thumbnailWidth), height);
}
boolean success = false;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(outputFile));
success = ImageIO.write(bufferedThumbnail, "jpeg", bos);
} catch(Exception e){
// to-do
}finally {
try { bos.flush(); } catch (Exception e) {}
try { bos.close(); } catch (Exception e) {}
}
return success;
}
|
cs |