本文實例講述了PHP實現(xiàn)對圖片的反色處理功能。分享給大家供大家參考,具體如下:
今天有個需求用php對圖片進行反色,和轉(zhuǎn)灰,之前不知道可不可行,后來看到了imagefilter()
函數(shù),用來轉(zhuǎn)灰綽綽有余,好強大;
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轉(zhuǎn)色代碼:
?php /** * 主要用于圖片的處理函數(shù) */ //圖片的反色功能 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); //獲取顏色的數(shù)組 $color = imagecolorsforindex($img, $index); //顏色值的反轉(zhuǎn) $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);
原圖(以小編常用的這副毀童年惡搞圖為例):
運行后(這里以測試為主,至于圖片顛覆三觀還是五官,小編就不多過問了~):
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP圖形與圖片操作技巧匯總》、《php文件操作總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP網(wǎng)絡編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。