PHP заменяет цветной пиксель прозрачным

Я хочу сделать простой логотип с прочным backgroung с прозрачным, поэтому я решил взять первый пиксель и установить этот цвет на все изображение как прозрачное, я знаю, что это не лучшее решение для всех, но я думаю, что обложки большинство случаев.

Проблема в том, что пиксель, который он окрашивает в черный, прозрачно, это мой код:

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

И мои функции класса:

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

Наконец я решил это таким образом

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

Я создал истинное изображение с альфа-каналом и без алфавитов.

BR