change color of image pixel by pixel

六眼飞鱼酱① 提交于 2020-01-01 19:36:16

问题


I an trying to change color of a png image so that transparent area still remain transparent and give rest of the image a color this is what i tried

<?php

$im = imagecreatefrompng('2.png');
$w = imagesx($im);
$h = imagesy($im);

$om = imagecreatetruecolor($w,$h);

for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {
        $rgb = imagecolorat($im, $x, $y);
        $colors = imagecolorsforindex($im,  $rgb);

        $orgb = imagecolorallocate($om,$colors['alpha'],$colors['alpha'],$colors['alpha']);
        imagesetpixel($om,$x,$y,$orgb);
    }
}

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

imagedestroy($om);
imagedestroy($im);

?>   

It produce image like: Before

After

i am still not getting an exact idea how can i get highlighted area of png image and give them a color such as yellow or pink without loosing transparency so that only non-transparent area will get remain transparent


回答1:


You should be able to work with the palette instead of going through every pixel in that case:

<?PHP
    $myRed = 255;
    $myGreen = 0;
    $myBlue = 0;

    $im = imagecreatefrompng('http://s25.postimg.org/ll0dzblan/image.png');
    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    if (imageistruecolor($im))
    {
        $sx = imagesx($im);
        $sy = imagesy($im);
        for ($x = 0; $x < $sx; $x++)
        {
            for ($y = 0; $y < $sy; $y++)
            {
                $c = imagecolorat($im, $x, $y);
                $a = $c & 0xFF000000;
                $newColor = $a | $myRed << 16 | $myGreen << 8 | $myBlue;
                imagesetpixel($im, $x, $y, $newColor );
            }
        }
    } else {
        $numColors = imagecolorstotal($im);
        $transparent = imagecolortransparent($im);

        for ($i=0; $i < $numColors; $i++)
        {
            if ($i != $transparent)
                imagecolorset($im, $i, $myRed, $myGreen, $myBlue, $myAlpha);

        }
    }

    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
?>


来源:https://stackoverflow.com/questions/23543051/change-color-of-image-pixel-by-pixel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!