썸네일(Thumbnail) 만들기

2017. 1. 2. 15:32Programming/Spring

1) 라이브러리 없이


<ImgFileUploadUtil.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
public String makeThumbnail(int thumbnail_width, int thumbnail_height){
    String thumbnailName = null;
    if(newFileFlag){
       try{
           //file 중에서 image를 읽어온다.
           BufferedImage originImage = ImageIO.read(newFile);
           thumbnailName="thumb_"+newFilename;
           thumbFile = new File(savePath,thumbnailName);
           //기존 이미지가 썸네일보다 작으면 수정할 필요 없다.
           if(!(originImage.getWidth()<=thumbnail_width && originImage.getHeight()<=thumbnail_height)){
               //이미지 썸네일로 만들기(그릇 준비 -> 그래픽 만들기 -> 그리기 -> 데이터로 쓰기)
               BufferedImage thumbImage = 
                 new BufferedImage(thumbnail_width, thumbnail_height, BufferedImage.TYPE_3BYTE_BGR);
               Graphics2D graphic = thumbImage.createGraphics();
               graphic.drawImage(originImage, 00, thumbnail_width, thumbnail_height, null);
               ImageIO.write(thumbImage, extension, thumbFile);
           }else{
           }
       }catch(Exception e){e.printStackTrace();}
    }
    return thumbnailName;
}
 
cs



2) Scalr 라이브러리 사용시


<<차이점>>

ㄱ. 매개변수 : width 필요 없이 height만

ㄴ. 그리는 과정 없이 resize 메소드를 사용


<ImgFileUploadUtil.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
public String makeThumbnail(int thumbnail_height){ //높이 비율로 가로를 조정
   String thumbnailName = null;
   if(newFileFlag){
     try{
        BufferedImage originImage = ImageIO.read(newFile);
        thumbnailName="thumb_"+newFilename;
        thumbFile = new File(savePath,thumbnailName);
        if(!(originImage.getHeight()<=thumbnail_height)){
           //Scalr 라이브러리 : 그리는 과정을 resize로 생략해줌
           BufferedImage thumbImage = Scalr.resize(originImage, Scalr.Method.QUALITY, Mode.FIT_TO_HEIGHT, thumbnail_height);
           ImageIO.write(thumbImage, extension, thumbFile);
        }else{//이미 파일이 썸네일보다 작을 때 그냥 복사한다.
           byte[] newFiledata = FileCopyUtils.copyToByteArray(newFile);
           FileCopyUtils.copy(newFiledata, thumbFile);
        }
     }catch(Exception e){e.printStackTrace();}
   }
   return thumbnailName;
}
 
cs