<?php
/*
----------------------------------------------------------------------
函數:調整圖片尺寸或生成縮略圖
修改:2009-8-8
返回:True/False
參數:
$Image 需要調整的圖片(含路徑)
$Dw=450 調整時最大寬度;縮略圖時的絕對寬度
$Dh=450 調整時最大高度;縮略圖時的絕對高度
$Type=1 1,調整尺寸; 2,生成縮略圖
作者:Seven(QQ:9256114)WWW.7DI.NET*/
$path='img/';//路徑
$phtypes=array(
'img/gif',
'img/jpg',
'img/jpeg',
'img/bmp',
'img/pjpeg',
'img/x-png'
);
FunctionImg($Image,$Dw=450,$Dh=450,$Type=1){
IF(!File_Exists($Image)){
ReturnFalse;
}
#如果需要生成縮略圖,則將原圖拷貝一下重新給$Image賦值
IF($Type!=1){
Copy($Image,Str_Replace(".","_x.",$Image));
$Image=Str_Replace(".","_x.",$Image);
}
#取得文件的類型,根據不同的類型建立不同的對象
$ImgInfo=GetImageSize($Image);
Switch($ImgInfo[2]){
Case1:
$Img =@ImageCreateFromGIF($Image);
Break;
Case2:
$Img =@ImageCreateFromJPEG($Image);
Break;
Case3:
$Img =@ImageCreateFromPNG($Image);
Break;
}
#如果對象沒有創建成功,則說明非圖片文件
IF(Empty($Img)){
#如果是生成縮略圖的時候出錯,則需要刪掉已經複製的文件
IF($Type!=1){Unlink($Image);}
ReturnFalse;
}
#如果是執行調整尺寸操作則
IF($Type==1){
$w=ImagesX($Img);
$h=ImagesY($Img);
$width = $w;
$height = $h;
IF($width>$Dw){
$Par=$Dw/$width;
$width=$Dw;
$height=$height*$Par;
IF($height>$Dh){
$Par=$Dh/$height;
$height=$Dh;
$width=$width*$Par;
}
}ElseIF($height>$Dh){
$Par=$Dh/$height;
$height=$Dh;
$width=$width*$Par;
IF($width>$Dw){
$Par=$Dw/$width;
$width=$Dw;
$height=$height*$Par;
}
}Else{
$width=$width;
$height=$height;
}
$nImg =ImageCreateTrueColor($width,$height); #新建一個真彩色畫布
ImageCopyReSampled($nImg,$Img,0,0,0,0,$width,$height,$w,$h);#重採樣拷貝部分圖像並調整大小
ImageJpeg($nImg,$Image); #以JPEG格式將圖像輸出到瀏覽器或文件
ReturnTrue;
#如果是執行生成縮略圖操作則
}Else{
$w=ImagesX($Img);
$h=ImagesY($Img);
$width = $w;
$height = $h;
$nImg =ImageCreateTrueColor($Dw,$Dh);
IF($h/$w>$Dh/$Dw){#高比較大
$width=$Dw;
$height=$h*$Dw/$w;
$IntNH=$height-$Dh;
ImageCopyReSampled($nImg,
$Img,0,-$IntNH/1.8,0,0,
$Dw, $height,
$w, $h);
}Else{ #寬比較大
$height=$Dh;
$width=$w*$Dh/$h;
$IntNW=$width-$Dw;
ImageCopyReSampled($nImg,
$Img,-$IntNW/1.8,0,0,0,
$width, $Dh,
$w, $h);
}
ImageJpeg($nImg,$Image);
ReturnTrue;
}
}
?>
<html><body>
<form method="post"
enctype="multipart/form-data" name="form1">
<table>
<tr><td>上傳圖片</td></tr>
<tr><td><input
type="file" name="photo"
size="20"/></td></tr>
<tr><td><input
type="submit" value="上傳"/></td></tr>
</table>
允許上傳的文件類型爲:<?=implode(', ',$phtypes)?></form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
if(!is_uploaded_file($_FILES["photo"][tmp_name])){
echo "圖片不存在";
exit();
}
if(!is_dir('img')){//路徑若不存在則創建
mkdir('img');
}
$upfile=$_FILES["photo"];
$pinfo=pathinfo($upfile["name"]);
$name=$pinfo['basename'];//文件名
$tmp_name=$upfile["tmp_name"];
$file_type=$pinfo['extension'];//獲得文件類型
$showphpath=$path.$name;
if(in_array($upfile["type"],$phtypes)){
echo "文件類型不符!";
exit();
}
if(move_uploaded_file($tmp_name,$path.$name)){
echo "成功!";
Img($showphpath,100,800,2);
}
echo "<img src=\"".$showphpath."\"
/>";
}
?>
</body>
</html>