Thumbnails 를 사용 하여 그림 지정 크기 압축 실현

프로젝트 에 서 는 업로드 서버 의 그림 크기 를 판단 하고 500 k 이상 의 그림 은 압축 처리 하여 500 k 이하 로 업로드 하도록 요구 합 니 다.
자바 api 의 ImageIO 를 통 해 이미지 압축 을 실현 할 수 있 지만 인터넷 블 로 그 를 보면 bug 가 많 고 OOM 메모리 가 넘 치 는 현상 이 있다 고 합 니 다.
Thumbnails 플러그 인 은 Google 의 플러그 인 으로 서로 다른 인 자 를 지정 하여 압축 작업 을 할 수 있 습 니 다.
예 를 들 어 너비(size),크기 조정(scale),품질 비(outputQuality)제정 등 이다.
플러그 인 이 사용 하 는 jar 패 키 지 는:
thumbnailator-0.4.8.jar
코드 는 다음 과 같 습 니 다:

 /**
 * 
 * @param srcPath      
 * @param desPath       
 * @param desFileSize       ,  kb
 * @param accuracy   ,       ,    0.9
 * @return
 */
 public static String commpressPicForScale(String srcPath,String desPath,
 long desFileSize , double accuracy){
 try {
 File srcFile = new File(srcPath);
 long srcFilesize = srcFile.length();
 System.out.println("   :"+srcPath + ",  :" + srcFilesize/1024 + "kb");
 //    ,          desFileSize
 commpressPicCycle(desPath, desFileSize, accuracy);
 
 File desFile = new File(desPath);
 System.out.println("    :" + desPath + ",  " + desFile.length()/1024 + "kb");
 System.out.println("      !");
 } catch (Exception e) {
 e.printStackTrace();
 }
 return desPath;
 }

 public static void commpressPicCycle(String desPath , long desFileSize,
 double accuracy) throws IOException{
 File imgFile = new File(desPath);
 long fileSize = imgFile.length();
 //    ,    500k,   ,      500k,  
 if(fileSize <= desFileSize * 500){
 return;
 }
 //    
 BufferedImage bim = ImageIO.read(imgFile);
 int imgWidth = bim.getWidth();
 int imgHeight = bim.getHeight();
 int desWidth = new BigDecimal(imgWidth).multiply(
  new BigDecimal(accuracy)).intValue();
 int desHeight = new BigDecimal(imgHeight).multiply(
  new BigDecimal(accuracy)).intValue();
 Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
 //       ,        1M   
 commpressPicCycle(desPath, desFileSize, accuracy);
 }
그리고 그림 크기 를 압축 합 니 다.

commpressPicForScale(filePath, filePath, 500, 0.8);
압축 완료:

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기