不變形截圖的PHP代碼

來源:互聯網
上載者:User
  1. function my_image_resize($src_file, $dst_file , $new_width , $new_height)
  2. {
  3. $src_img=imagecreatefromjpeg($src_file);
  4. $w=imagesx($src_img);
  5. $h=imagesy($src_img);
  6. $ratio_w=1.0 * $new_width / $w;
  7. $ratio_h=1.0 * $new_height / $h;
  8. $ratio=1.0;
  9. // 產生的映像的高寬比原來的都小,或都大 ,原則是 取大比例放大,取大比例縮小(縮小的比例就比較小了)
  10. if( ($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1))
  11. {
  12. if($ratio_w < $ratio_h)
  13. {
  14. $ratio = $ratio_h ; // 情況一,寬度的比例比高度方向的小,按照高度的比例標準來裁剪或放大
  15. }else {
  16. $ratio = $ratio_w ;
  17. }
  18. // 定義一個中間的臨時映像,該映像的寬高比 正好滿足目標要求
  19. $inter_w=(int)($new_width / $ratio);
  20. $inter_h=(int) ($new_height / $ratio);
  21. $inter_img=imagecreatetruecolor($inter_w , $inter_h);
  22. imagecopy($inter_img, $src_img, 0,0,0,0,$inter_w,$inter_h);
  23. // 產生一個以最大邊長度為大小的是靶心圖表像$ratio比例的臨時映像
  24. // 定義一個新的映像
  25. $new_img=imagecreatetruecolor($new_width,$new_height);
  26. imagecopyresampled($new_img,$inter_img,0,0,0,0,$new_width,$new_height,$inter_w,$inter_h);
  27. //imagejpeg($new_img, $dst_file,100); // 儲存映像
  28. }
  29. // end if 1
  30. // 2 靶心圖表像 的一個邊大於原圖,一個邊小於原圖 ,先放大平普映像,然後裁剪
  31. //if( ($ratio_w < 1 && $ratio_h > 1) || ($ratio_w >1 && $ratio_h <1) )
  32. else
  33. {
  34. $ratio=$ratio_h>$ratio_w? $ratio_h : $ratio_w; //取比例大的那個值
  35. // 定義一個中間的大映像,該映像的高或寬和靶心圖表像相等,然後對原圖放大
  36. $inter_w=(int)($w * $ratio);
  37. $inter_h=(int) ($h * $ratio);
  38. $inter_img=imagecreatetruecolor($inter_w , $inter_h);
  39. //將原圖縮放比例後裁剪
  40. imagecopyresampled($inter_img,$src_img,0,0,0,0,$inter_w,$inter_h,$w,$h);
  41. // 定義一個新的映像
  42. $new_img=imagecreatetruecolor($new_width,$new_height);
  43. imagecopy($new_img, $inter_img, 0,0,0,0,$new_width,$new_height);
  44. }
  45. imagejpeg($new_img, $dst_file,100); // 儲存映像
  46. }
  47. $filename = "110.jpg"; //原圖片的路徑
  48. $fileto="120.jpg";//後儲存的路徑
  49. $new_w=300;//設定的寬
  50. $new_h=350; //設定的高
  51. my_image_resize($filename,$fileto,$new_w,$new_h);
  52. ?>
複製代碼
不變形, PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.