duangan6133 2013-03-21 07:24
浏览 117
已采纳

使用GD更改图像颜色

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.

  • 写回答

1条回答 默认 最新

  • dsaxw4201 2013-03-21 07:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接