廢話不多說,直接上代碼:
if(move_uploaded_file($arrFile['tmp_name'], $strPicName)){
switch ($FileExt) {
case ".gif": //gif
$im = imagecreatefromgif($strPicName);
break;
case ".png": //png
$im = imagecreatefrompng($strPicName);
break;
default: //jpg
$im = imagecreatefromjpeg($strPicName);
break;
}
//擷取圖片資訊
$imageInfo = $this->getInfo($strPicName);
//建新畫布,進行縮放,保持透明
if (function_exists("imagecreatetruecolor")) {//GD2.0.1
$new = imagecreatetruecolor(150, 80);
$this->addTranByListImage($FileExt,$new);
ImageCopyResampled($new, $im, 0, 0, 0, 0, 150, 80, $imageInfo["width"], $imageInfo["height"]);
}else{
$new = imagecreate(150, 80);
$this->addTranByListImage($FileExt,$new);
ImageCopyResized($new, $im, 0, 0, 0, 0, 150, 80, $imageInfo["width"], $imageInfo["height"]);
}
//產生縮圖
switch ($FileExt) {
case ".gif": //gif
imagegif($new,$strPicName);
break;
case ".png": //png
imagepng($new,$strPicName);
break;
default: //jpg
imagejpeg($new,$strPicName);
break;
}
//產生灰圖
if ($new && imagefilter($new, IMG_FILTER_GRAYSCALE)) {
imagepng($new, $strPicName."_grey.png");
return $strPhoto;
} else {
check::AlertExit('灰圖產生失敗!',-1);
}
}else{
check::AlertExit($strPicName.'檔案上傳錯誤!',-1);
}
前面的上傳上面的代碼就不重複寫了,我們直接從move_uploaded_file這裡開始。
上傳好檔案後根據檔案路徑擷取$im對象,也就是imagecreateXXX出來的東西。$ FileExt是擷取的圖片尾碼。其他內容注釋應該也寫的很清楚了。主要看一下這兩個方法:$this->getInfo($strPicName);和$this->addTranByListImage($FileExt,$new);
$this->getInfo();其實很簡單,擷取圖片的資訊而已:
function getInfo($file){
$data = getimagesize($file);
$imageInfo["width"] = $data[0];
$imageInfo["height"]= $data[1];
$imageInfo["type"] = $data[2];
$imageInfo["name"] = basename($file);
return $imageInfo;
}
而$this->addTranByListImage()則是我們今天的重點:
function addTranByListImage($FileExt,$img){
switch ($FileExt) {
case ".gif": //gif
case ".png": //png
imagealphablending($img, true);
imagesavealpha($img, true);
$trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $trans_colour);
break;
default: //jpg
break;
}
}
其實也是很簡單的方法,剛剛在百度上搜到的加到了程式裡並測試完成。如果是正常情況下,上傳的帶背景的透明的png圖片在縮放或者某些操作後,圖片的透明背景就變能黑的了,而這幾句代碼正是保證背景依然是透明效果的關鍵語句。
至於灰圖就更簡單了imagefilter方法,後面的參數自己百度一下吧,都是常量。
------------------------------------------------
使用Word2007發布,片未顯示或提示有附件但無附件的,請移步至獨立部落格查看完整文章!
文章修改及增加內容僅在獨立部落格中更改!
我的獨立部落格:壊小子 - http://www.zyblog.net/
本文連結:http://www.zyblog.net/post-83.html
歡迎轉載,轉載請註明本文來源。