2013-03-21 89 views
0

我想了解PHP中的圖像操作並編寫一些代碼來編輯照片。用GD改變圖像顏色

所以,我正在閱讀關於imagefilter()函數,但我想手動編輯collors。

我有一小片與ImageFilter的代碼做一個形象深褐色

imagefilter($image, IMG_FILTER_GRAYSCALE); 
imagefilter($image, IMG_FILTER_COLORIZE, 55, 25, -10); 
imagefilter($image, IMG_FILTER_CONTRAST, -10); 

我想這樣做,但沒有ImageFilter中的();有可能的?

我明白它可能會獲取圖像中的顏色,然後更改它們並重新繪製它;

爲了讓圖像色彩我有這樣的:

$rgb = imagecolorat($out, 10, 15); 
$colors = imagecolorsforindex($out, $rgb); 

而這種打印:

array(4) { 
    ["red"]=> int(150) 
    ["green"]=> int(100) 
    ["blue"]=> int(15) 
    ["alpha"]=> int(0) 

}

,我可以編輯這些值,並將其融入圖片?

我將不勝感激任何形式的幫助:書籍,教程,代碼片斷。

回答

2

使用imagesetpixel()函數。由於此功能需要使用顏色標識符作爲第三個參數,因此您需要使用imagecolorallocate()來創建一個。

下面這減半每種顏色的色值的示例代碼:現在,這裏

$rgb = imagecolorat($out, 10, 15); 
$colors = imagecolorsforindex($out, $rgb); 

$new_color = imagecolorallocate($out, $colors['red']/2, $colors['green']/2, $colors['blue']/2); 
imagesetpixel($out, 10, 15, $new_color); 

一個簡單的灰度濾鏡:

list($width, $height) = getimagesize($filename); 
$image = imagecreatefrompng($filename); 
$out = imagecreatetruecolor($width, $height); 

for($y = 0; $y < $height; $y++) { 
    for($x = 0; $x < $width; $x++) { 
     list($red, $green, $blue) = array_values(imagecolorsforindex($image, imagecolorat($image, $x, $y))); 

     $greyscale = $red + $green + $blue; 
     $greyscale /= 3; 

     $new_color = imagecolorallocate($out, $greyscale, $greyscale, $greyscale); 
     imagesetpixel($out, $x, $y, $new_color); 
    } 
} 

imagedestroy($image); 
header('Content-Type: image/png'); 
imagepng($out); 
imagedestroy($out); 

小心使用imagecolorallocate一個循環內,你可以不會分配比imagecolorstotal更多的顏色返回到單個圖像中。如果達到極限imagecolorallocate將返回false,您可以使用imagecolorclosest獲取已分配的壁櫥顏色。

+0

不起作用! – 2013-03-21 07:38:24

+0

我測試了它,它適用於我,你是如何測試它的? – MarcDefiant 2013-03-21 07:43:26

+0

$ image = imagecreatefromjpeg($ _ photo); $ rgb = imagecolorat($ image,10,15); $ colors = imagecolorsforindex($ image,$ rgb); var_dump($ colors); (color)['red']/4,$ colors ['green']/4,$ colors ['blue']/4); $ color = ['blue']/4); imagesetpixel($ image,10,15,$ new_color); imagejpeg($ image,'grayscale-sun.jpg'); imagedestroy($ image); echo'Image With A Grayscale Effect Applied'; – 2013-03-21 07:45:30