Santiago
Santiago

Reputation: 2320

PHP replace a color pixel by a transparente one

I want to make in a easy way a logo with solid backgroung with a transparent one, so I decide to take the first pixel and set that color on all the image as transparent, I know is not the best solution for all but I think covers most cases.

The problem is the pixel it's coloring black insted transparent, this is my code:

$im = $this->loadImage($targetFile);
$this->replaceImageColor($im, imagecolorat($im, 0, 0), imageColorAllocateAlpha($im, 255, 255, 255, 127));
imagepng($im, 'test.png');

And my class functions:

function loadImage($imagePath) {
    $resource = false;
    if( strstr($imagePath, '.jpg') || strstr($imagePath, '.jpeg') )
        $resource = @imagecreatefromjpg($imagePath);
    if( strstr($imagePath, '.png') )
        $resource = @imagecreatefrompng($imagePath);

    return $resource;
}

function replaceImageColor($img, $from, $to) {
    // pixel by pixel grid.
    for ($y = 0; $y < imagesy($img); $y++) {
        for ($x = 0; $x < imagesx($img); $x++) {
            // find hex at x,y
            $at = imagecolorat($img, $x, $y);
            // set $from to $to if hex matches.
            if ($at == $from) 
                imagesetpixel($img, $x, $y, $to);
        }
    }
}

Upvotes: 1

Views: 2165

Answers (1)

Santiago
Santiago

Reputation: 2320

Finally I solved it in this way

$im = $this->loadImage($targetFileIcon);
$out = $this->transparentColorImage($im, imagecolorat($im, 0, 0));
imagepng($out, 'test.png');
imagedestroy($im);
imagedestroy($out);

function loadImage($imagePath) {
    $resource = false;
    if( strstr($imagePath, '.jpg') || strstr($imagePath, '.jpeg') )
        $resource = @imagecreatefromjpg($imagePath);
    if( strstr($imagePath, '.png') )
        $resource = @imagecreatefrompng($imagePath);

    return $resource;
}

function transparentColorImage($img, $color) {
    // pixel by pixel grid.
    $out = ImageCreateTrueColor(imagesx($img),imagesy($img));
    imagesavealpha($out, true);
    imagealphablending($out, false);
    $white = imagecolorallocatealpha($out, 255, 255, 255, 127);
    imagefill($out, 0, 0, $white);
    for ($y = 0; $y < imagesy($img); $y++) {
        for ($x = 0; $x < imagesx($img); $x++) {
            // find hex at x,y
            $at = imagecolorat($img, $x, $y);
            // set $from to $to if hex matches.
            if ($at != $color)
                imagesetpixel($out, $x, $y, $at);
        }
    }
    return $out;
}

I created a true image with alpha channel and no alphablending.

BR

Upvotes: 1

Related Questions