在php中生成縮略圖是程序開發中常用的,下面我找了幾個不錯的php生成縮略圖的實現程序,有需要的朋友可使用,本人親測絕對好用哦。
創建圖像縮略圖需要許多時間,此代碼將有助於了解縮略圖的邏輯。
代碼如下 復制代碼
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
$ext = explode(".", $filename);
$ext = $ext[count($ext)-1];
if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax)
return $im;
if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
例2
代碼如下 復制代碼function creat_thumbnail($img,$w,$h,$path)
{
$org_info = getimagesize($img); //獲得圖像大小且是通過post傳遞過來的
//var_dump($org_info);
//Array ( [0] => 1024 [1] => 768 [2] => 3 [3] => width="1024" height="768" [bits] => 8 [mime] => image/png )
$orig_x = $org_info[0]; //圖像寬度
$orig_y = $org_info[1]; //圖像高度
$orig_type = $org_info[2]; //圖片類別即後綴 1 = GIF,2 = JPG,3 = PNG,
//是真彩色圖像
if (function_exists("imagecreatetruecolor"))
{
switch($orig_type)
{
//從給定的gif文件名中取得的圖像
case 1 : $thumb_type = ".gif"; $_creatImage = "imagegif"; $_function = "imagecreatefromgif";
break;
//從給定的jpeg,jpg文件名中取得的圖像
case 2 : $thumb_type = ".jpg"; $_creatImage = "imagejpeg"; $_function = "imagecreatefromjpeg";
break;
//從給定的png文件名中取得的圖像
case 3 : $thumb_type = ".png"; $_creatImage = "imagepng"; $_function = "imagecreatefrompng";
break;
}
}
//如果從給定的文件名可取得的圖像
if(function_exists($_function))
{
$orig_image = $_function($img); //從給定的$img文件名中取得的圖像
}
if (($orig_x / $orig_y) >= (4 / 3)) //如果寬/高 >= 4/3
{
$y = round($orig_y / ($orig_x / $w)); //對浮點數進行四捨五入
$x = $w;
}
else //即 高/寬 >= 4/3
{
$x = round($orig_x / ($orig_y / $h));
$y = $h;
}
$sm_image = imagecreatetruecolor($x, $y); //創建真彩色圖片
//重采樣拷貝部分圖像並調整大小
Imagecopyresampled($sm_image, $orig_image, 0, 0, 0, 0, $x, $y, $orig_x, $orig_y);
//imageJPEG($sm_image, '', 80); //在浏覽器輸出圖像
$tnpath = $path."/"."s_".date('YmdHis').$thumb_type; //縮略圖的路徑
$thumbnail = @$_creatImage($sm_image, $tnpath, 80); //生成圖片,成功返回true(或1)
imagedestroy ($sm_image); //銷毀圖像
if($thumbnail==true)
{
return $tnpath;
}
}