[java] 원본 이미지 가지고 썸네일 생성[BufferedImage]
원본 이미지의 파일 경로를 가지고,
썸네일을 따로 저장하는 기능과, 저장없이 썸네일을 만들어서 뿌려주는 기능이다.
/**
* make jang.jae
* imgUrl = 파일 경로
* w = 변경할 width, 없을경우 원본 사이즈
* h = 변경할 height, 없을경우 원본 사이즈
* outPath = 값이 있으면 해당 경로에 저장, 없으면 호출한 영역에 이미지 노출
*/
public void imgOnload(String imgUrl, String w, String h, String outPath, HttpServletResponse response) throws Exception{
int extIndex = imgUrl.lastIndexOf(".");
String fileExt = imgUrl.substring(extIndex+1);
BufferedImage sourceImage= ImageIO.read(new File(imgUrl));
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
int param_w=0;
int param_h=0;
if(w==null){
param_w=width;
}else{
param_w=Integer.parseInt(w);
}
if(h==null){
param_h=height;
}else{
param_h=Integer.parseInt(h);
}
byte[] buffer = null;
BufferedImage img = new BufferedImage(param_w, param_h, BufferedImage.TYPE_INT_RGB);
Image scaledImage = sourceImage.getScaledInstance(param_w,param_h, Image.SCALE_SMOOTH);
img.createGraphics().drawImage(scaledImage, 0, 0, null);
BufferedImage img2 = new BufferedImage(param_w, param_h ,BufferedImage.TYPE_INT_RGB);
img2 = img.getSubimage(0, 0, param_w, param_h);
if(outPath !=null){
OutputStream os =new FileOutputStream(outPath);
ImageIO.write(img2, fileExt, os);
os.close();
}else{
OutputStream os =response.getOutputStream();
ImageIO.write(img2, fileExt, os);
os.close();
}
}