图片压缩

来源:互联网 发布:淘宝摄影和美工 编辑:程序博客网 时间:2024/05/02 20:20

public void proce(String oldFile, int width, int height, float quality,
   String smallIcon) {

  String newImage = null;
  try {

   Image srcFile = ImageIO.read(new File(oldFile));

   double rate1 = ((double) srcFile.getWidth(null)) / (double) width;
   double rate2 = ((double) srcFile.getHeight(null)) / (double) height;
   double rate = rate1 > rate2 ? rate1 : rate2;
   int new_w = (int) (((double) srcFile.getWidth(null)) / rate);
   int new_h = (int) (((double) srcFile.getHeight(null)) / rate);

   BufferedImage tag = new BufferedImage(new_w, new_h,
     BufferedImage.TYPE_INT_RGB);
   tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);
   String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.'));

   newImage = filePrex + smallIcon
     + oldFile.substring(filePrex.length());

   FileOutputStream out = new FileOutputStream(newImage);

   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);

   jep.setQuality(quality, true);
   encoder.encode(tag, jep);

   out.close();
   srcFile.flush();
   srcFile = null;

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

原创粉丝点击