当前位置:编程学习 > JAVA >>

java图片批量压缩+全部压缩

/*
oldsrc  : 原图片地址文件夹 如 'd:/'
   newsrc  : 压缩后图片地址文件夹 如 'e:/'
   widthdist,heightdist : 压缩后的宽和高
  
   createtime 2010-11-25
   @auto yijianfeng
 */
public void reduceImgAll(String oldsrc, String newsrc, int widthdist,
   int heightdist) {
  try {
   File file = new File(oldsrc);
   if (!file.exists()) {
    return;
   }
   File[] srcfile = file.listFiles();
   if (srcfile != null) {
    for (int i = 0; i < srcfile.length; i++) {
     if (srcfile[i].isFile()
       && (srcfile[i].getName().endsWith(".jpg")
         || srcfile[i].getName().endsWith(".JPG")
         || srcfile[i].getName().endsWith(".gif") || srcfile[i]
         .getName().endsWith(".gif"))) {
      Image src = javax.imageio.ImageIO.read(srcfile[i]);
      BufferedImage tag = new BufferedImage((int) widthdist,
        (int) heightdist, BufferedImage.TYPE_INT_RGB);
      tag.getGraphics().drawImage(
        src.getScaledInstance(widthdist, heightdist,
          Image.SCALE_SMOOTH), 0, 0, null);
      FileOutputStream out = new FileOutputStream(newsrc
        + srcfile[i].getName());
      JPEGImageEncoder encoder = JPEGCodec
        .createJPEGEncoder(out);
      System.out.println(oldsrc + "/" + srcfile[i].getName());
      encoder.encode(tag);
      out.close();
     } else {
      reduceImgAll(oldsrc + srcfile[i].getName(), newsrc,
        widthdist, heightdist);
     }
    }
   }
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }

 


摘自 玩转java

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,