废话不多说,直接上代码:
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
欢迎转载,转载请注明本文来源。