title: PHP GD - Color Replacement with Alpha gives images a border
body: <p>I am not sure if the function below works for the most part or not at all. What i am trying to is loop through the pixels and switch the color while maintaining the alpha. I thought I had it working till I made my page background white and saw a small border around the icon.</p>
  
  <p>I thought that the problem was that the color was being applied to a semi transparent pixel. Thus white turned grey into lighter grey on the anti-aliased parts of the images. I decided then to make the pixel completely transparent before setting the new color. This did nothing.</p>
  
  <p>So the question. Why do white images have a small border?</p>
  
  <p>The color conversion function.</p>
  
  <pre><code>function updateThumb($image, $newColor) {
      $img = imagecreatefrompng($image);
  
      $w = imagesx($img);
      $h = imagesy($img);
  
      // Work through pixels
      for($y=0;$y&lt;$h;$y++) {
          for($x=0;$x&lt;$w;$x++) {
              // Apply new color + Alpha
              $rgb = imagecolorsforindex($img, imagecolorat($img, $x, $y));
  
          $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
          imagesetpixel($img, $x, $y, $transparent);
  
              $pixelColor = imagecolorallocatealpha($img, $newColor[0], $newColor[1], $newColor[2], $rgb['alpha']);
              imagesetpixel ($img, $x, $y, $pixelColor);
          }
      }
  
      // Restore Alpha
      imageAlphaBlending($img, true);
      imageSaveAlpha($img, true);
  
      return $img;
  }
  </code></pre>
  
  <p>Thumbs need a rollover effect so the image is made in the function below. I don't believe this has anything to do with the issue, I have tried changing the above function to create the image and not return it and the same thing happens.</p>
  
  <pre><code>function makeThumb($path, $top, $bottom=FALSE) {
      $width = imagesx($top);
      $height = imagesy($top);
  
      $thumbHeight = $bottom != FALSE ? $height * 2 : $height;
  
      // Create Transparent PNG
      $thumb = imagecreatetruecolor($width, $thumbHeight);
      $transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
      imagefill($thumb, 0, 0, $transparent);
  
      // Copy Top Image
      imagecopy($thumb, $top, 0, 0, 0, 0, $width, $height);
  
      // Copy Bottom Image
      if ($bottom != FALSE) {
          imagecopy($thumb, $bottom, 0, $height, 0, 0, $width, $height);
      }
  
      // Save Image with Alpha
      imageAlphaBlending($thumb, true);
      imageSaveAlpha($thumb, true);
      imagepng($thumb, $path); // save image as gif
  
  }
  </code></pre>
  
  <p>functions are called like this...</p>
  
  <pre><code>$thumbTop = updateThumb('Path/To/Thumb', array(255,255,255));
  makeThumb('output/path', $thumbTop);
  </code></pre>
  
  <p>This is the icon: <a href="http://img171.imageshack.us/i/iconkc.png/" rel="nofollow">http://img171.imageshack.us/i/iconkc.png/</a></p>
  
  <p>Any ideas?</p>