首页 > 开发 > PHP > 正文

PHP实现对图片的反色处理功能【测试可用】

2024-05-04 22:43:59
字体:
来源:转载
供稿:网友

本文实例讲述了PHP实现对图片的反色处理功能。分享给大家供大家参考,具体如下:

今天有个需求用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);

原图(以小编常用的这副毁童年恶搞图为例):

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

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP图形与图片操作技巧汇总》、《php文件操作总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php面向对象程序设计入门教程》、《PHP网络编程技巧总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表