时间:2021-07-01 10:21:17 帮助过:32人阅读
今天有个需求用php对图片进行反色,和转灰,之前不知道可不可行,后来看到了imagefilter()函数,用来转灰绰绰有余,好强大;
imagefilter($im, IMG_FILTER_GRAYSCALE)
当然也有人在css里面设置变灰
<style type="text/css">
img {
-webkit-filter: grayscale(1);/* Webkit */
filter:gray;/* IE6-9 */
filter: grayscale(1);/* W3C */
}
</style>php转色代码:
<?php
/**
* 主要用于图片的处理函数
*/
//图片的反色功能
function color($url) {
//获取图片的信息
list($width, $height, $type, $attr)= getimagesize($url);
$imagetype = strtolower(image_type_to_extension($type,false));
$fun = 'imagecreatefrom'.($imagetype == 'jpg'?'jpeg':$imagetype);
$img = $fun($url);
for ($y=0; $y < $height; $y++) {
for ($x=0; $x <$width; $x++) {
//获取颜色的所以值
$index = imagecolorat($img, $x, $y);
//获取颜色的数组
$color = imagecolorsforindex($img, $index);
//颜色值的反转
$red = 256 - $color['red'];
$green = 256 - $color['green'];
$blue = 256 - $color['blue'];
$hex = imagecolorallocate($img, $red, $green, $blue);
//给每一个像素分配颜色值
imagesetpixel($img, $x, $y, $hex);
}
}
//输出图片
switch ($imagetype) {
case 'gif':
imagegif($img);
break;
case 'jpeg':
imagejpeg($img);
break;
case 'png':
imagepng($img);
break;
default:
break;
}
}测试代码:
$imgurl='1.jpg'; echo color($imgurl);
原图(以小编常用的这副毁童年恶搞图为例):

运行后(这里以测试为主,至于图片颠覆三观还是五官,小编就不多过问了~):

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
推荐阅读:
php实现解析xml并生成sql语句步骤详解
PHP实现正则表达式分组捕获步骤详解
以上就是PHP实现对图片的反色处理步骤详解的详细内容,更多请关注Gxl网其它相关文章!