ホームページ  >  記事  >  バックエンド開発  >  PHP でサーバー側で画像のサイズを変更する方法の紹介

PHP でサーバー側で画像のサイズを変更する方法の紹介

黄舟
黄舟オリジナル
2017-07-26 13:48:091370ブラウズ

この記事では主にPHPでサーバー側で画像をリサイズする方法を紹介しています。imageResizerとloadimageの関連スキルを分析して画像を操作したい人は参考にしてください。

この記事の例ではリサイズの実装について説明します。 PHP のサーバー側のイメージ。皆さんの参考に共有してください。具体的な分析は次のとおりです:

画像サイズの調整をサーバー側で完了すると、ブラウザーでの処理に比べて多くの利点があります。
この記事では、PHPでサーバー側で画像のサイズを変更する方法を紹介します。

コードは 2 つの部分で構成されます:

① imageResizer() は画像を処理するために使用されます
② loadimage() は画像の URL をより単純な形式で挿入します


<?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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。