Java与PHP生成缩略图或者大小压缩的方式

jopen 8年前

java

package com.app.image;  import java.io.*;  import java.util.Date;  import java.awt.*;  import java.awt.image.*;  import javax.imageio.ImageIO;  import com.sun.image.codec.jpeg.*;  /**   * 图片压缩处理   * @author 崔素强   */  public class ImageThumbOrCompress {   private Image img;   private int width;   private int height;      public static void main(String[] args) throws Exception {    System.out.println("开始:" + new Date().toLocaleString());    ImageThumbOrCompress imgCom = new ImageThumbOrCompress("D:/Droid4x/test.jpg");    imgCom.resizeFix(400, 400);    System.out.println("结束:" + new Date().toLocaleString());   }   /**    * 构造函数    */   public ImageThumbOrCompress(String fileName) throws IOException {    File file = new File(fileName);// 读入文件    img = ImageIO.read(file);      // 构造Image对象    width = img.getWidth(null);    // 得到源图宽    height = img.getHeight(null);  // 得到源图长   }   /**    * 按照宽度还是高度进行压缩    * @param w int 最大宽度    * @param h int 最大高度    */   public void resizeFix(int w, int h) throws IOException {    if (width / height > w / h) {     resizeByWidth(w);    } else {     resizeByHeight(h);    }   }   /**    * 以宽度为基准,等比例放缩图片    * @param w int 新宽度    */   public void resizeByWidth(int w) throws IOException {    int h = (int) (height * w / width);    resize(w, h);   }   /**    * 以高度为基准,等比例缩放图片    * @param h int 新高度    */   public void resizeByHeight(int h) throws IOException {    int w = (int) (width * h / height);    resize(w, h);   }   /**    * 强制压缩/放大图片到固定的大小    * @param w int 新宽度    * @param h int 新高度    */   public void resize(int w, int h) throws IOException {    // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢    BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );         /*    image.getGraphics().drawImage(      img.getScaledInstance(newWidth, newHeight,        Image.SCALE_SMOOTH), 0, 0, null);    **/    image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图    File destFile = new File("D:/Droid4x/test2.jpg");    FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流    // 可以正常实现bmp、png、gif转jpg    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    encoder.encode(image); // JPEG编码    out.close();   }  }

另外,在jdk6以上实现了图片大小不变,质量改变的压缩

package com.app.image;    import java.awt.image.BufferedImage;  import java.awt.image.ColorModel;  import java.io.File;  import java.io.FileOutputStream;    import javax.imageio.IIOImage;  import javax.imageio.ImageIO;  import javax.imageio.ImageWriteParam;  import javax.imageio.ImageWriter;      public class ImageQualityCompress {        public static void main(String[] args)      {          if(compressPic("D:/Droid4x/test.jpg", "D:/Droid4x/test3.jpg"))          {              System.out.println("压缩成功!");           }          else          {              System.out.println("压缩失败!");           }      }        public static boolean compressPic(String srcFilePath, String descFilePath)      {          File file = null;          BufferedImage src = null;          FileOutputStream out = null;          ImageWriter imgWrier;          ImageWriteParam imgWriteParams;            // 指定写图片的方式为 jpg          imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();          imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);          // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT          imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);          // 这里指定压缩的程度,参数qality是取值0~1范围内,          imgWriteParams.setCompressionQuality(0.1f);          imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);                    ColorModel colorModel = ColorModel.getRGBdefault();          // 指定压缩时使用的色彩模式          imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel                  .createCompatibleSampleModel(16, 16)));            try          {              if(srcFilePath==null || srcFilePath.length()==0)              {                  return false;              }              else              {                  file = new File(srcFilePath);                  src = ImageIO.read(file);                  out = new FileOutputStream(descFilePath);                    imgWrier.reset();                  // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造                  imgWrier.setOutput(ImageIO.createImageOutputStream(out));                  // 调用write方法,就可以向输入流写图片                  imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);                  out.flush();                  out.close();              }          }          catch(Exception e)          {              e.printStackTrace();              return false;          }          return true;      }  }

php

//by MoreWindows (http://blog.csdn.net/MoreWindows )  class CImage  {      /**       * 生成保持原图纵横比的缩略图,支持.png .jpg .gif       * 缩略图类型统一为.png格式       * $srcFile     原图像文件名称       * $toW         缩略图宽       * $toH         缩略图高       * $toFile      缩略图文件名称,为空覆盖原图像文件       * @return bool          */      public static function CreateThumbnail($srcFile, $toW, $toH, $toFile="")       {          if ($toFile == "")          {                  $toFile = $srcFile;           }          $info = "";          //返回含有4个单元的数组,0-宽,1-高,2-图像类型,3-宽高的文本描述。          //失败返回false并产生警告。          $data = getimagesize($srcFile, $info);          if (!$data)              return false;                    //将文件载入到资源变量im中          switch ($data[2]) //1-GIF,2-JPG,3-PNG          {          case 1:              if(!function_exists("imagecreatefromgif"))              {                  echo "the GD can't support .gif, please use .jpeg or .png! <a href='javascript:history.back();'>back</a>";                  exit();              }              $im = imagecreatefromgif($srcFile);              break;                        case 2:              if(!function_exists("imagecreatefromjpeg"))              {                  echo "the GD can't support .jpeg, please use other picture! <a href='javascript:history.back();'>back</a>";                  exit();              }              $im = imagecreatefromjpeg($srcFile);              break;                          case 3:              $im = imagecreatefrompng($srcFile);                  break;          }                    //计算缩略图的宽高          $srcW = imagesx($im);          $srcH = imagesy($im);          $toWH = $toW / $toH;          $srcWH = $srcW / $srcH;          if ($toWH <= $srcWH)           {              $ftoW = $toW;              $ftoH = (int)($ftoW * ($srcH / $srcW));          }          else           {              $ftoH = $toH;              $ftoW = (int)($ftoH * ($srcW / $srcH));          }                    if (function_exists("imagecreatetruecolor"))           {              $ni = imagecreatetruecolor($ftoW, $ftoH); //新建一个真彩色图像              if ($ni)               {                  //重采样拷贝部分图像并调整大小 可保持较好的清晰度                  imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);              }               else               {                  //拷贝部分图像并调整大小                  $ni = imagecreate($ftoW, $ftoH);                  imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);              }          }          else           {              $ni = imagecreate($ftoW, $ftoH);              imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);          }            //保存到文件 统一为.png格式          imagepng($ni, $toFile); //以 PNG 格式将图像输出到浏览器或文件          ImageDestroy($ni);          ImageDestroy($im);          return true;      }  }


来自: http://my.oschina.net/ososchina/blog/482951