前段時間由於項目需要,要實現圖片上傳並且壓縮生成縮略圖的功能。
接口代碼如下:
$allowext = array ( 'png', 'jpg', 'jpeg', 'gif','mp4','doc');
$fileElement = 'file';
$filepath_rel = 'userfiles/upload/chatfile/'.date("Ymd")."/"; // 相對路徑
//這里的$FILE_PATH 是網站的根目錄
$filepath_abs = $FILE_PATH . $filepath_rel; // 絕對路徑
if(!file_exists($filepath_abs))
{
mkdir($filepath_abs,0777,true); }
$fup = new FileUpload ( '100M', $allowext );
$r = $fup->upload ( $fileElement, $filepath_abs, '', true );
$name_abs = $filepath_abs . $r;
$name_rel = $filepath_rel . $r;
//圖片等比例壓縮
$pic = $fup->getThumb($FILE_PATH,$name_rel,300,300);
//upload 方法實現圖片上傳
//參數$elename : file域的名稱。<input type='file' name='elename'/>
//$newname --上傳以后的名字;可以為空。
//$savepath --文件保存路徑,一定要以 “/” 結尾。
//$auto_rename 是否自動重命名
//如果$newname 為空 且 auto_rename 為false ,將保留原來的文件名字
function upload($elename, $savepath, $newname = '', $auto_rename = false){
if(empty($_FILES[$elename])) throw new Exception('沒有上傳文件或文件大小超過系統限制', 981);
$f_name = basename($_FILES[$elename]["name"]); //被上傳文件的名稱
$f_type = $_FILES[$elename]["type"]; //被上傳文件的類型
$f_size = $_FILES[$elename]["size"]; //被上傳文件的大小,以字節計
$f_tmpname = $_FILES[$elename]["tmp_name"]; //存儲在服務器的文件的臨時副本的名稱
$f_error = $_FILES[$elename]["error"]; //由文件上傳導致的錯誤代碼
//是否發生錯誤
if($f_error) $this->uploadFileError($f_error);
//文件后綴
$f_ext = $this->getFileExt($f_name);
//檢查上傳類型
//--是否在禁止列表
$forbidext = $this->forbidext;
if(in_array($f_ext, $forbidext)) {
throw new Exception('文件類型禁止上傳', 901);
}
//--是否在允許列表
$allowext = $this->allowext;
if(!in_array($f_ext, $allowext)) {
throw new Exception('文件類型未被允許', 902);
}
//文件大小是否允許
$allowsize = $this->allowsize;
if($f_size > $allowsize) {
throw new Exception('文件超過允許的大小', 903);
}
//文件是否是上傳的文件
if(!is_uploaded_file($f_tmpname)) {
throw new Exception('非上傳的文件', 904);
}
//文件重命名 按時間命名 方便查看
if(empty($newname) && $auto_rename)
$new_name = $this->setFileNameByDate().'.'.$f_ext;
elseif(!empty($newname))
$new_name = $newname.'.'.$f_ext;
else
$new_name = $f_name;
//保存文件
$f_path = $savepath.$new_name;
if(move_uploaded_file($f_tmpname, $f_path)){
return $new_name;//上傳成功,返回文件名。
}else{
throw new Exception('文件寫入失敗,請檢查上傳目錄是否可寫', 905);
}
}
//生成一個日期命名的文件名
private function setFileNameByDate(){
return date('YmdHis').rand(1000,9999);
}
完成了上傳文件的功能接下來就要對這個文件進行壓縮處理了。在這里用到了在腳本之家學習到的方法,做了一些改變。
function resizeImage($im, $dest, $maxwidth, $maxheight) {
$img = getimagesize($im);
switch ($img[2]) {
case 1:
$im = @imagecreatefromgif($im);
break;
case 2:
$im = @imagecreatefromjpeg($im);
break;
case 3:
$im = @imagecreatefrompng($im);
break;
}
$pic_width = imagesx($im);
$pic_height = imagesy($im);
$resizewidth_tag = false;
$resizeheight_tag = false;
if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
if ($maxwidth && $pic_width > $maxwidth) {
$widthratio = $maxwidth / $pic_width;
$resizewidth_tag = true;
}
if ($maxheight && $pic_height > $maxheight) {
$heightratio = $maxheight / $pic_height;
$resizeheight_tag = true;
}
if ($resizewidth_tag && $resizeheight_tag) {
if ($widthratio < $heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if ($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio;
if ($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if (function_exists("imagecopyresampled")) {
$newim = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
} else {
$newim = imagecreate($newwidth, $newheight);
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
}
imagejpeg($newim, $dest);
imagedestroy($newim);
} else {
imagejpeg($im, $dest);
}
}
function getThumb($public_path,$sFile,$iWidth,$iHeight){
//圖片公共路徑 $public_path 這里改為有外部傳入 根據具體情況進行修改
//判斷該圖片是否存在
if(!file_exists($public_path.$sFile)) return $sFile;
//判斷圖片格式(圖片文件后綴)
$extend = explode("." , $sFile);
$attach_fileext = strtolower($extend[count($extend) - 1]);
if (!in_array($attach_fileext, array('jpg','png','jpeg'))){
return '';
}
//壓縮圖片文件名稱
$sFileNameS = str_replace(".".$attach_fileext, "_".$iWidth.'_'.$iHeight.'.'.$attach_fileext, $sFile);
//判斷是否已壓縮圖片,若是則返回壓縮圖片路徑
if(file_exists($public_path.$sFileNameS)){
return $sFileNameS;
}
//生成壓縮圖片,並存儲到原圖同路徑下
self::resizeImage($public_path.$sFile, $public_path.$sFileNameS, $iWidth, $iHeight);
if(!file_exists($public_path.$sFileNameS)){
return $sFile;
}
return $sFileNameS;
}
這樣上傳的圖片就按給定的width、height按相同比例壓縮 這里resizeImage指定了最大的寬,高也可根據實際需求情況去調整。