本文共 2491 字,大约阅读时间需要 8 分钟。
废话不多说,直接上代码:
if(move_uploaded_file($arrFile['tmp_name'], $strPicName)){ switch ($FileExt) { case ".gif": $im = imagecreatefromgif($strPicName); break; case ".png": $im = imagecreatefrompng($strPicName); break; default: $im = imagecreatefromjpeg($strPicName); break; } //获取图片信息 $imageInfo = $this->getInfo($strPicName); //建新画布,进行缩放,保持透明 if (function_exists("imagecreatetruecolor")) { $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": imagegif($new, $strPicName); break; case ".png": imagepng($new, $strPicName); break; default: 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);} $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": case ".png": imagealphablending($img, true); imagesavealpha($img, true); $trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127); imagefill($img, 0, 0, $trans_colour); break; default: break; }} 其实也是很简单的方法,刚刚在百度上搜到的加到了程序里并测试完成。如果是正常情况下,上传的带背景的透明的 PNG 图片在缩放或者某些操作后,图片的透明背景就变成了黑的了,而这几句代码正是保证背景依然是透明效果的关键语句。
至于灰图就更简单了,imagefilter 方法,后面的参数自己百度一下吧,都是常量。
文章修改及增加内容仅在独立博客中更改!
我的独立博客:壊小子 - http://www.zyblog.net/
本文链接:http://www.zyblog.net/post-83.html
欢迎转载,转载请注明本文来源。
转载于: https://www.cnblogs.com/charleszhang/archive/2012/07/31/2616931.html