php圖片裁剪與縮圖樣本

來源:互聯網
上載者:User

在php編程中,經常會遇到圖片太大且規格不統一的情況,顯示的控制需要靠JavaScript來完成,用在行動裝置上時顯示效果不好且流量巨大,需要對現有圖片庫的圖片進行一次處理,產生符合行動裝置用的縮圖,將原來用戶端JS做的工作轉移到伺服器端用PHP的GD庫來集中處理。

要求,圖片源與需要的大小:

  1. list($src_w,$src_h)=getimagesize($src_img); // 擷取原圖尺寸
  2. $dst_scale = $dst_h/$dst_w; //靶心圖表像長寬比
  3. $src_scale = $src_h/$src_w; // 原圖長寬比
  4. if($src_scale>=$dst_scale)
  5. {
  6. // 過高
  7. $w = intval($src_w);
  8. $h = intval($dst_scale*$w);
  9. $x = 0;
  10. $y = ($src_h - $h)/3;
  11. }
  12. else
  13. {
  14. // 過寬
  15. $h = intval($src_h);
  16. $w = intval($h/$dst_scale);
  17. $x = ($src_w - $w)/2;
  18. $y = 0;
  19. }
  20. // 剪裁
  21. $source=imagecreatefromjpeg($src_img);
  22. $croped=imagecreatetruecolor($w, $h);
  23. imagecopy($croped,$source,0,0,$x,$y,$src_w,$src_h);
  24. // 縮放
  25. $scale = $dst_w/$w;
  26. $target = imagecreatetruecolor($dst_w, $dst_h);
  27. $final_w = intval($w*$scale);
  28. $final_h = intval($h*$scale);
  29. imagecopyresampled($target,$croped,0,0,0,0,$final_w,$final_h,$w,$h);
  30. // 儲存
  31. $timestamp = time();
  32. imagejpeg($target, "$timestamp.jpg");
  33. imagedestroy($target);
  34. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.