php 用GD庫產生高品質的縮圖範例程式碼

怪我咯
發布: 2023-03-13 18:22:01
原創
1353 人瀏覽過

在網站上GD庫通常用來產生縮圖,或是用來為圖片加浮水印,或是用來產生漢字驗證碼,或是對網站資料產生報表等。在PHP處理影像,可使用GD庫,而GD庫開始時是支援GIF的,但由於GIF使用了有版權爭議的LZW演算法,會引起法律問題,於是從GD 庫1.6 版起所有的GIF 支援都移除了,但又在GD 庫2.0.28 版起又加回來了。如果使用二者之間版本的 GD 函式庫時 GIF 相關函數不可用。本篇主要介紹php 以GD函式庫產生高品質的縮圖的範例程式碼

以下是PHP原始碼(ResizeImage.php)。 

<?php 
$FILENAME="image.thumb"; 
// 生成图片的宽度 
$RESIZEWIDTH=400; 
// 生成图片的高度 
$RESIZEHEIGHT=400; 

function ResizeImage($im,$maxwidth,$maxheight,$name){ 
$width = imagesx($im); 
$height = imagesy($im); 
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ 
if($maxwidth && $width > $maxwidth){ 
$widthratio = $maxwidth/$width; 
$RESIZEWIDTH=true; 
} 
if($maxheight && $height > $maxheight){ 
$heightratio = $maxheight/$height; 
$RESIZEHEIGHT=true; 
} 
if($RESIZEWIDTH && $RESIZEHEIGHT){ 
if($widthratio < $heightratio){ 
$ratio = $widthratio; 
}else{ 
$ratio = $heightratio; 
} 
}elseif($RESIZEWIDTH){ 
$ratio = $widthratio; 
}elseif($RESIZEHEIGHT){ 
$ratio = $heightratio; 
} 
$newwidth = $width * $ratio; 
$newheight = $height * $ratio; 
if(function_exists("imagecopyresampled")){ 
$newim = imagecreatetruecolor($newwidth, $newheight); 
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
}else{ 
$newim = imagecreate($newwidth, $newheight); 
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
} 
ImageJpeg ($newim,$name . ".jpg"); 
ImageDestroy ($newim); 
}else{ 
ImageJpeg ($im,$name . ".jpg"); 
} 
} 

if($_FILES[&#39;image&#39;][&#39;size&#39;]){ 
if($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/pjpeg"){ 
$im = imagecreatefromjpeg($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
}elseif($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/x-png"){ 
$im = imagecreatefrompng($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
}elseif($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/gif"){ 
$im = imagecreatefromgif($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
} 
if($im){ 
if(file_exists("$FILENAME.jpg")){ 
unlink("$FILENAME.jpg"); 
} 
ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME); 
ImageDestroy ($im); 
} 
} 
?>
登入後複製

以下是測試程式碼(demo.php) 程式碼如下:

<?php 
include(&#39;ResizeImage.php&#39;); 
if(!empty($_POST)){ 
echo($FILENAME.".jpg?cache=".rand(0,999999)); 
} 
?> 
<form name="test" action="?submit=true" enctype="multipart/form-data" method="post" > 
<input type="file" name="image" size="50" value="浏览"><p> 
<input type="submit" value="上传图片"> 
</form>
登入後複製


以上是php 用GD庫產生高品質的縮圖範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!