본문 바로가기
Java

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

by 전재훈 2015. 7. 3.
반응형

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.File;


import javax.imageio.ImageIO;


import com.mortennobel.imagescaling.AdvancedResizeOp;

import com.mortennobel.imagescaling.ResampleOp;



public class Main {

public static void main( String args[] ) {

int thumbWidth = 600;

File originFile = new File("C:" + File.separator + "IU2.jpg");

thumb( originFile,  thumbWidth );

thumb2( originFile, thumbWidth );

}

// 일반 썸네일

public static void thumb(File originFile, int thumbWidth) {

String thumbPath = "C:" + File.separator;

try {

// 디렉토리 없으면 디렉토리 생성

File thumbDir = new File(thumbPath);

if(!thumbDir.exists()) {   

thumbDir.mkdirs();

       }

// 원본파일 버퍼 생성

BufferedImage originFileBuffer = ImageIO.read( originFile ) ;

// 썸네일 높이 계산

int originWidth = originFileBuffer.getWidth();

int originHeight = originFileBuffer.getHeight();

int thumbHeight = originHeight * thumbWidth / originWidth ;

// 썸네일 파일 버퍼 생성

BufferedImage thumbFileBuffer = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_3BYTE_BGR);

// 확장자 체크 및 원본 경로

int lastIndex = originFile.getName().lastIndexOf(".");

String fileExt = originFile.getName().substring( lastIndex+1 );

// 썸네일 파일 생성

File thumbFile =  new File(   thumbPath + "thumb_" + originFile.getName() );

Graphics2D graphic = thumbFileBuffer.createGraphics();

graphic.drawImage(originFileBuffer, 0, 0, thumbWidth, thumbHeight, null);

ImageIO.write( thumbFileBuffer, fileExt  , thumbFile );

System.out.println( thumbFile.getName() + "썸네일 생성완료");

} catch (Exception e) {

e.printStackTrace();

}

}

// 화질 좋은 썸네일 > java-image-scaling-0.8.6.jar 와 Filters.jar Build And Path에 추가 필요

// https://code.google.com/p/java-image-scaling/ 여기서 java-image-scaling.jar 받을 수 있고 전 Filters.jar은 구글링해서 찾았습니다.

public static void thumb2( File originFile, int thumbWidth ) {

String thumbPath = "C:" + File.separator;

try {

// 디렉토리 없으면 디렉토리 생성

File thumbDir = new File(thumbPath);

if(!thumbDir.exists()) {   

thumbDir.mkdirs();

        }


// 원본파일 버퍼 생성

BufferedImage originFileBuffer = ImageIO.read( originFile ) ;

// 썸네일 높이 계산

int originWidth = originFileBuffer.getWidth();

int originHeight = originFileBuffer.getHeight();

int thumbHeight = originHeight * thumbWidth / originWidth ;

// 확장자 체크 및 원본 경로

int lastIndex = originFile.getName().lastIndexOf(".");

String fileExt = originFile.getName().substring( lastIndex+1 );


ResampleOp resampleOp = new ResampleOp( thumbWidth, thumbHeight) ;

resampleOp.setUnsharpenMask( AdvancedResizeOp.UnsharpenMask.Soft );

BufferedImage rescaledImage = resampleOp.filter( originFileBuffer, null );

// 썸네일 파일 생성

File thumbFile =  new File(   thumbPath + "new_thumb_" + originFile.getName() );

ImageIO.write( rescaledImage, fileExt, thumbFile );

System.out.println( thumbFile.getName() + " 썸네일 생성완료");

} catch (Exception e) {

e.printStackTrace();

}

}


}



반응형

댓글