博客
关于我
PHP图片处理—PNG透明缩放并生成灰图
阅读量:793 次
发布时间:2023-03-01

本文共 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

你可能感兴趣的文章
PHP加密与安全的最佳实践
查看>>
PHP加速器eaccelerator导致php-fpm进程卡死原因分析
查看>>
PHP区分 企业微信浏览器 | 普通微信浏览器 | 其他浏览器
查看>>
php原生代码怎么连表查询,PHP tp5中使用原生sql查询代码实例
查看>>
PHP去掉转义符
查看>>
php去除字符串开头或末尾的字符(例如逗号)
查看>>
php反射api
查看>>
PHP反射ReflectionClass、ReflectionMethod 入门教程
查看>>
PHP反射机制
查看>>
php取当天的最后一秒_Docker快速搭建PHP开发环境详细教程
查看>>
php取绝对值
查看>>
PHP变量内容的获取
查看>>
php各种常用的算法
查看>>
php各种缓存策略对比
查看>>
RabbitMQ高级特性 - 消息分发(限流、负载均衡)
查看>>
php后台“爬虫”模拟登录第三方系统
查看>>
php后台的在控制器中就可以实现阅读数增加
查看>>
php命令行生成项目结构
查看>>
php命名空间
查看>>
PHP命名空间带来的干扰
查看>>