//檢查 GD
function checkGD(){
$error = false;
$gd = array();
if (!extension_loaded('gd')) {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
if (!dl('php_gd.dll')) {
$error = true;
}
} else {
if (!dl('gd.so')) {
$error = true;
}
}
}
if ($error) {
return false;
} else {
$gdInfo = gd_info();
$gd['version'] = stristr($gdInfo['GD Version'], '2.') ? 2 : 1;
$gd['formats']['gif'] = $gdInfo['GIF Read Support'];
$gd['formats']['jpg'] = $gdInfo['JPEG Support']; //小心,不是 JPG Support
$gd['formats']['png'] = $gdInfo['PNG Support'];
return $gd;
}
}
// 製作縮圖 createImage(來源檔名路徑, 格式, 縮圖檔名路徑, 縮圖寬, 縮圖高)
function createImage($file, $format, $fileDest, $outputX, $outputY){
// Get information about the installed GD.
$gdInfo = checkGD();
$gdVersion = $gdInfo['version'];
if ($gdInfo == false) {
return false;
}
// Ensure the given format is supported.
if ($gdInfo['formats'][$format] != 1) {
return false;
}
// Get the image dimensions.
$dimensions = @getimagesize($file);
$width = $dimensions[0];
$height = $dimensions[1];
// thumbs mode.
$quality = 85;
$deltaX = 0;
$deltaY = 0;
$portionX = $width;
$portionY = $height;
// Get the source image in gif format.
if ($format == 'gif') {
$imageSrc = @imagecreatefromgif($file);
}
// Get the source image in jpg format.
if ($format == 'jpg') {
$imageSrc = @imagecreatefromjpeg($file);
}
// Get the source image in png format.
if ($format == 'png') {
$imageSrc = @imagecreatefrompng($file);
}
// The thumbnail creation with GD1.x functions does the job.
if ($gdVersion == 1) {
// Create an empty thumbnail image.
$imageDest = @imagecreate($outputX, $outputY);
// Try to create the thumbnail from the source image.
if (@imagecopyresized($imageDest, $imageSrc, 0, 0, $deltaX, $deltaY, $outputX, $outputY, $portionX, $portionY)) {
// save the thumbnail image into a file.
@imagejpeg($imageDest, $fileDest, $quality);
// Delete both image resources.
@imagedestroy($imageSrc);
@imagedestroy($imageDest);
return true;
}
}
// The recommended approach is the usage of the GD2.x functions.
if ($gdVersion == 2) {
// Create an empty thumbnail image.
$imageDest = @imagecreatetruecolor($outputX, $outputY);
// Try to create the thumbnail from the source image.
if (@imagecopyresampled($imageDest, $imageSrc, 0, 0, $deltaX, $deltaY, $outputX, $outputY, $portionX, $portionY)) {
// save the thumbnail image into a file.
@imagejpeg($imageDest, $fileDest, $quality);
// Delete both image resources.
@imagedestroy($imageSrc);
@imagedestroy($imageDest);
return true;
}
}
return false;
}
2011年5月10日 星期二
檢查 GD 並產生縮圖的函式
這是經常使用的GD縮圖函式
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言