PNG 24 with the GD library

I’m having trouble saving an image as png after some color manipulation.

Here is the original image

Here is the image after imagepng();

Here is the code


//$this->resource = imagecreatefrompng( 'the.png' );

//color::hexToRGB coverts hex to an array() containing RGB values

$search = color::hexToRGB ( $search );
		
$replace = color::hexToRGB ( $replace );
		
$width = $this->fileSize [ 0 ];
$height = $this->fileSize [ 1 ];
		
for($i=0;$i<$width;$i++)
        {
            for($j=0;$j<$height;$j++)
            {
             $index = imagecolorat($this->resource,$i,$j);
			
			$cIndex = imagecolorsforindex($this->resource, $index);
			
			if( $cIndex['red'] == $search [0] && $cIndex['green'] ==  $search [1] && $cIndex['blue'] ==  $search [2]){
			
				$colorB = imagecolorallocatealpha( $this->resource, $replace [0], $replace [1], $replace [2], 0 );
				imagesetpixel($this->resource, $i, $j, $colorB);
			}
			
			 
            }
                 
        }
$imgname = "result.png";
if(file_exists($imgname)) unlink($imgname);
		
imagepng($this->resource, $imgname );

That is the code the class I used. it seems to change the color properly but as you can see, the rounded part of the image gets all squary.