首頁  >  文章  >  後端開發  >  php實作在伺服器端完成圖片大小的調整

php實作在伺服器端完成圖片大小的調整

墨辰丷
墨辰丷原創
2018-06-09 17:23:351411瀏覽

這篇文章主要介紹php實現在伺服器端完成圖片大小的調整,有興趣的朋友參考下,希望對大家有幫助。

本文實例講述了php實作在伺服器端調整圖片大小的方法。具體分析如下:

在伺服器端完成圖片大小的調整,會比在瀏覽器的處理有很多的好處。
本文介紹了PHP如何在伺服器端調整圖片大小。

程式碼包含兩部分:

① imageResizer() is used to process the image
② loadimage() inserts the image url in a simpler format

<?php
 function imageResizer($url, $width, $height) {
  header(&#39;Content-type: image/jpeg&#39;);
  list($width_orig, $height_orig) = getimagesize($url);
  $ratio_orig = $width_orig/$height_orig;
  if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
  } else {
   $height = $width/$ratio_orig;
  }
  // This resamples the image
  $image_p = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($url);
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
  // Output the image
  imagejpeg($image_p, null, 100);
 }
 //works with both POST and GET
 $method = $_SERVER[&#39;REQUEST_METHOD&#39;];
 if ($method == &#39;GET&#39;) {
  imageResize($_GET[&#39;url&#39;], $_GET[&#39;w&#39;], $_GET[&#39;h&#39;]);
  } elseif ($method == &#39;POST&#39;) {
  imageResize($_POST[&#39;url&#39;], $_POST[&#39;w&#39;], $_POST[&#39;h&#39;]);
  }
 // makes the process simpler
 function loadImage($url, $width, $height){
  echo &#39;image.php?url=&#39;, urlencode($url) ,
  &#39;&w=&#39;,$width,
  &#39;&h=&#39;,$height;
 }
?>
##用法:

//Above code would be in a file called image.php.
//Images would be displayed like this:
<img src="<?php loadImage(&#39;image.jpg&#39;, 50, 50) ?>" alt="" />

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

基於PHP取得某個月週次資訊

php實現發送和接收簡訊的功能

PHP處理會話的10個函數

以上是php實作在伺服器端完成圖片大小的調整的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn