1. 程式人生 > 程式設計 >PHP生成縮圖例項講解

PHP生成縮圖例項講解

封裝的方法函式:

<?php
	/**
  * 生成縮圖
  * $imgSrc     圖片源路徑
  * $thumbWidth   縮圖寬度
  * $thumbHeight  縮圖高度
  * $thumbSrc    縮圖路徑
  * $isCut     是否剪下圖片
  */
  function createThumbImg($imgSrc,$thumbWidth,$thumbHeight,$thumbSrc,$isCut = false) {
    //1.獲取圖片的型別
程式設計客棧    $type = substr(strrchr($imgSrc,"."),1);
    //2.初始化圖象
    if ($type == "jpg" || $type == "jpeg") {
			//建立一塊畫布,並從JPEG檔案或URL地址載入一副影象
      $sourceImg = imagecreatefromjpeg($imgSrc);
    }elseif ($type == "gif") {
			//建立一塊畫布,並從GIF檔案或URL地址載入一副影象
      $sourceImg = imagecreatefromgif($imgSrc);
    }elseif ($type == "png") {
			//建立一塊畫布,並從PNG檔案或URL地址載入一副影象
      $sourceImg = imagecreatefrompng($imgSrc);
    }
		elseif ($type == "wbmp") {
			//建立一塊畫布
程式設計客棧
,並從WBMP檔案或URL地址載入一副影象 $sourceImg = imagecreatefromwbmp($imgSrc); } //取得影象寬度 $width = imagesx($sourceImg); //取得影象高度 $height = imagesy($sourceImg); //3.生成圖象 //縮圖的圖象比例 $scale = ($thumbWidth) / ($thumbHeight); //源圖片的圖象比例 $ratio = ($width) / ($height); if (($isCut) == 1) { //高度優先 if ($ratio >= $scale) { //建立真彩圖像資源(imagecreatetruecolor()函式使用GDLibrary建立新的真彩色影象) $newimg = imagecreatetruecolor($thumbWidth,$thumbHeight); http://www.cppcns.com
//影象處理 imagecopyresampled($newimg,$sourceImg,0www.cppcns.com,(($height) * $scale),$height); //以JPEG格式將影象輸出到瀏覽器或檔案 ImageJpeg($newimg,$thumbSrc); } //寬度優先 if ($ratio < $scale) { $newimg = imagecreatetruecolor($thumbWidth,$thumbHeight); imagecopyresamp
程式設計客棧
led($newimg,$width,(($width) / $scale)); ImageJpeg($newimg,$thumbSrc); } } else { if ($ratio >= $scale) { $newimg = imagecreatetruecolor($thumbWidth,($thumbWidth) / $ratio); imagecopyresampled($newimg,($thumbWidth) / $ratio,$height); ImageJpeg($newimg,$thumbSrc); } if ($ratio < $scale) { $newimg = imagecreatetruecolor(($thumbHeight) * $ratio,$thumbHeight); imagecopyresampled($newimg,($thumbHeight) * $ratio,$thumbSrc); } } //銷燬影象 ImageDestroy($sourceImg); } ?>

呼叫示例:

<?php
	//圖片源路徑
	$imgSrc="D:/PHP/test/demo.jpg";
	//縮圖路徑
	$thumbSrc="D:/PHP/test/thumb.jpg";
	createThumbImg($path,100,$thumbSrc);
?>

到此這篇關於PHP生成縮圖例項講解的文章就介紹到這了,更多相關PHP生成縮圖內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!