I want to learn about images manipulation in PHP and write some code to edit photos.

So, I'm reading about imagefilter() function, but I want to edit the collors manually.

I have a little piece of code with imagefilter to do a image sepia

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

I want to do the same, but without imagefilter(); it is possible?

I have understood that it may be getting the colors in the image and then change them and re-paint it;

To get the image colors I have this:

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

And this prints:

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

}

As I can edit those values ​​and integrate them into the picture?

I would appreciate any kind of help: books, tutorials, code pieces.

有帮助吗?

解决方案

Use the imagesetpixel() function. Since this function needs an color identifier as third parameter you need to use imagecolorallocate() to create one.

Here an example code which halves the color values of each color:

$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);

Now here a simple greyscale filter:

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);

Be careful with using imagecolorallocate inside of a loop, you can not allocate more colors than imagecolorstotal returns inside of an single image. If you reached the limit imagecolorallocate will return false and you can use imagecolorclosest to get the closet color which already has been allocated.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top