逐像素更改图像的颜色 [英] change color of image pixel by pixel

查看:120
本文介绍了逐像素更改图像的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更改png图像的颜色,以使透明区域仍保持透明,并为图像的其余部分赋予颜色,这就是我尝试过的

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

之后

我仍然没有一个确切的主意,我如何才能获得png图像的突出显示区域并给它们提供黄色或粉红色等颜色而又不失去透明性,这样只有非透明区域才能保持透明

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

推荐答案

在这种情况下,您应该能够使用调色板而不是遍历每个像素:

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

这篇关于逐像素更改图像的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆