PHP图片处理—PNG透明缩放并生成灰图
发布日期:2025-05-04 05:02:17
浏览次数:9
分类:精选文章
本文共 2427 字,大约阅读时间需要 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
发表评论
最新留言
感谢大佬
[***.8.128.20]2026年05月20日 20时52分40秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
php实战第二十二天
2023-03-01
rabbitmq重启
2023-03-01
php实现上传(多个)文件函数封装
2023-03-01
php实现下载文件方法
2023-03-01
php实现单链表
2023-03-01
php实现图片背景换色功能
2023-03-01
php实现多个一维数组对应合并成二维数组
2023-03-01
php实现多关键字查找方法
2023-03-01
PHP实现微信公众号H5支付
2023-03-01
PHP实现微信公众号网页授权
2023-03-01
PHP实现微信小程序推送消息至公众号
2023-03-01
rabbitmq逻辑与开发
2023-03-01
php实现根据身份证获取年龄
2023-03-01
PHP实现的MongoDB数据增删改查
2023-03-01
PHP实现的SSO单点登录系统,拿走就用吧
2023-03-01
php实现短信验证功能
2023-03-01
php实现逆转数组
2023-03-01
PHP实现通过geoip获取IP地理信息
2023-03-01
PHP实现页面静态化、纯静态化及伪静态化
2023-03-01