当前位置:Gxlcms > PHP教程 > PHP实现对图片的反色处理功能【测试可用】

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

时间:2021-07-01 10:21:17 帮助过:82人阅读

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

今天有个需求用php对图片进行反色,和转灰,之前不知道可不可行,后来看到了imagefilter()函数,用来转灰绰绰有余,好强大;

  1. imagefilter($im, IMG_FILTER_GRAYSCALE)

当然也有人在css里面设置变灰

  1. <style type="text/css">
  2. img {
  3. -webkit-filter: grayscale(1);/* Webkit */
  4. filter:gray;/* IE6-9 */
  5. filter: grayscale(1);/* W3C */
  6. }
  7. </style>

php转色代码:

  1. <?php
  2. /**
  3. * 主要用于图片的处理函数
  4. */
  5. //图片的反色功能
  6. function color($url) {
  7. //获取图片的信息
  8.   list($width, $height, $type, $attr)= getimagesize($url);
  9.   $imagetype = strtolower(image_type_to_extension($type,false));
  10.   $fun = 'imagecreatefrom'.($imagetype == 'jpg'?'jpeg':$imagetype);
  11.   $img = $fun($url);
  12.   for ($y=0; $y < $height; $y++) {
  13.   for ($x=0; $x <$width; $x++) {
  14.     //获取颜色的所以值
  15.     $index = imagecolorat($img, $x, $y);
  16.     //获取颜色的数组
  17.     $color = imagecolorsforindex($img, $index);
  18.     //颜色值的反转
  19.     $red = 256 - $color['red'];
  20.     $green = 256 - $color['green'];
  21.     $blue = 256 - $color['blue'];
  22.     $hex = imagecolorallocate($img, $red, $green, $blue);
  23.     //给每一个像素分配颜色值
  24.     imagesetpixel($img, $x, $y, $hex);
  25.     }
  26.   }
  27.   //
输出图片   switch ($imagetype) {   case 'gif':   imagegif($img);   break;     case 'jpeg':   imagejpeg($img);   break;     case 'png':   imagepng($img);   break;     default:   break;   } }

测试代码:

  1. $imgurl='1.jpg';
  2. echo color($imgurl);

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

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

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

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

人气教程排行