无损压缩图片心得

发烧网pagespeed测速的时候,提示

Optimize images

Properly formatting and compressing images can save many bytes of data.

所以想研究下有什么好的无损压缩图片的方法:

 

相关资料如下:

smusher

php-lib-smushit

这二种方式是用 ysmush.it 云端服务来压缩图片的, 压缩效果还不错.我们可以用它来

对一些静态图片,logo等比较稳定的图片来进行无损压缩,提升下载速度,些接解决页面阻塞的问题.

但对用户上传的图片,这二种方式就不给力了.

所以得另寻对策..

看这里的文档说明

在服务器上安装jpegoptimOptiPNG,上传后调用相关的命令对目标图片进行无损压缩.

代码很简单,如下所示:

   1:  function compress_img($ext,$file_name)
   2:  {
   3:      $exts = array("png","bmp","gif","pnm","tiff");
   4:      if (in_array($ext,$exts)) {
   5:          exec("/usr/bin/optipng -o5 ".$file_name);
   6:      }
   7:      if ($ext == "jpg") {
   8:          exec("/usr/bin/jpegoptim -o --strip-all ".$file_name);
   9:      }
  10:  }
  11:    if (@move_uploaded_file($uploadFile['tmp_name'],$uploadFile['filename'])) {
  12:   
  13:              compress_img($ext,$uploadFile["filename"]);
  14:              if(!empty($size_arrray)) {
  15:                  foreach($size_arrray as $size) {
  16:                      $newFile    = resizeImage($size['width'],$size['height'],$uploadFile['filename'],$targetName,$ext);
  17:                      $upload_file['full_path']   = $uploadPath.$targetName.'_'.$size['width'].'X'.$size['height'].'.'.$ext;
  18:                      $upload_file['filename']    = $targetName.'_'.$size['width'].'X'.$size['height'].'.'.$ext;
  19:                      $file_list[] = $upload_file;
  20:                  }
  21:              }
  22:   
  23:          }
  24:   
  25:        

总结如下:

无损压缩图片,能提升页面的下载速度,减少服务器带宽的压力…开发时要针对具体的情况选择合适的图片.

Choose an appropriate image file format.

The type of an image can have a drastic impact on the file size. Use these guidelines:
  • PNGs are almost always superior to GIFs and are usually the best choice. IE 4.0b1+, Mac IE 5.0+, Opera 3.51+ and Netscape 4.04+ as well as all versions of Safari and Firefox fully support PNG, including transparency. IE versions 4 to 6 don't support alpha channel transparency (partial transparency) but they support 256-color-or-less PNGs with 1-bit transparency (the same that is supported for GIFs). IE 7 and 8 support alpha transparent PNGs except when an alpha opacity filter is applied to the element. You can generate or convert suitable PNGs with GIMP by using "Indexed" rather than "RGB" mode. If you must maintain compatibility with 3.x-level browsers, serve an alternate GIF to those browsers.
  • Use GIFs for very small or simple graphics (e.g. less than 10x10 pixels, or a color palette of less than 3 colors) and for images which contain animation. If you think an image might compress better as a GIF, try it as a PNG and a GIF and pick the smaller.
  • Use JPGs for all photographic-style images.
  • Do not use BMPs or TIFFs.

你可能感兴趣的:(压缩)