無損壓縮圖片心得

發燒網pagespeed測速的時候,提示

Optimize images

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

因此想研究下有什麼好的無損壓縮圖片的方法:css

 

相關資料以下:html

smushergit

php-lib-smushitgithub

這二種方式是用 ysmush.it 雲端服務來壓縮圖片的, 壓縮效果還不錯.咱們能夠用它來服務器

對一些靜態圖片,logo等比較穩定的圖片來進行無損壓縮,提高下載速度,些接解決頁面阻塞的問題.app

但對用戶上傳的圖片,這二種方式就不給力了.less

因此得另尋對策..ide

看這裏的文檔說明ui

在服務器上安裝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.
相關文章
相關標籤/搜索