天天看點

php圖檔縮略圖講解,PHP生成縮略圖執行個體講解

這篇文章主要介紹了PHP生成縮略圖執行個體講解,文章列舉了執行個體代碼,有正好需要的同學可以借鑒下。

封裝的方法函數:<?php

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);

//圖像處理

imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, (($height) * $scale), $height);

//以JPEG格式将圖像輸出到浏覽器或檔案

ImageJpeg($newimg, $thumbSrc);

}

//寬度優先

if ($ratio 

$newimg = imagecreatetruecolor($thumbWidth, $thumbHeight);

imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, (($width) / $scale));

ImageJpeg($newimg, $thumbSrc);

}

} else {

if ($ratio >= $scale) {

$newimg = imagecreatetruecolor($thumbWidth, ($thumbWidth) / $ratio);

imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, ($thumbWidth) / $ratio, $width, $height);

ImageJpeg($newimg, $thumbSrc);

}

if ($ratio 

$newimg = imagecreatetruecolor(($thumbHeight) * $ratio, $thumbHeight);

imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, ($thumbHeight) * $ratio, $thumbHeight, $width, $height);

ImageJpeg($newimg, $thumbSrc);

}

}

//銷毀圖像

ImageDestroy($sourceImg);

}

?>

調用示例:<?php

//圖檔源路徑

$imgSrc="D:/PHP/test/demo.jpg";

//縮略圖路徑

$thumbSrc="D:/PHP/test/thumb.jpg";

createThumbImg($path,100,100,$thumbSrc);

?>