title: Partial black background when watermarking PNG image with GD PHP
body: <p>I have pieced together a PHP class to perform various image related functions using GD functions of PHP.</p>
  
  <p>It works great for all image types. Rotate, flip, resize, crop and to a lesser extent, watermark.</p>
  
  <p>All but the latter work perfectly. For example after a few changes, rotated PNG images retained their transparency whereas before they were losing that and the background turning black. Common problem, it appears. But all working now.</p>
  
  <p>Where I'm still getting stuck is watermarking a PNG image with another PNG image. It appears to work fine with JPG and other images. This is the code (simplified):</p>
  
  <pre><code>public function writeWatermarkSimple()
  {
      $watermarkFile = 'watermark.png';
      $watermarkImage = imagecreatefrompng($watermarkFile);
  
      imagealphablending($watermarkImage, false);
      imagesavealpha($watermarkImage, true);
  
      $imageFile = 'image.png';
      $baseImage = imagecreatefrompng($imageFile);
  
      imagealphablending($baseImage, false);
      imagesavealpha($baseImage, true);
  
      $marginH = imagesx($baseImage) - imagesx($watermarkImage);
      $marginV = imagesy($baseImage) - imagesy($watermarkImage);
  
      $cut = imagecreatetruecolor(imagesx($watermarkImage), imagesy($watermarkImage));
      imagecopy($cut, $baseImage, 0, 0, $marginH, $marginV, imagesx($watermarkImage), imagesy($watermarkImage));
      imagecopy($cut, $watermarkImage, 0, 0, 0, 0, imagesx($watermarkImage), imagesy($watermarkImage));
  
      imagecopymerge($baseImage, $cut, $marginH, $marginV, 0, 0, imagesx($watermarkImage), imagesy($watermarkImage), 80);
  
      if (!imagepng($baseImage, 'watermarked_image.png'))
      {
          return false;
      }
  
      return true;
  }
  </code></pre>
  
  <p>This has been pieced together with various guides and advice people have given based on a similar issue. Again, working perfectly with JPG images and PNG watermarks, but not PNG &amp; PNG.</p>
  
  <p>Some example images:</p>
  
  <p><a href="http://i.imgur.com/hHRWinj.png" rel="nofollow">http://i.imgur.com/hHRWinj.png</a> - This is the watermark I'm using.
  <a href="http://i.imgur.com/6sy8Ncs.png" rel="nofollow">http://i.imgur.com/6sy8Ncs.png</a> - This is the image I'm applying the watermark to.
  <a href="http://i.imgur.com/ghovYLm.png" rel="nofollow">http://i.imgur.com/ghovYLm.png</a> - This is the end result.</p>
  
  <p>The bit I find interesting is that any part of the watermark that is overlaid on a non-transparent portion of the image is working fine. Just the rest of it has the black background.</p>
  
  <p>This leads me to believe I'm close, and I hope that the expertise of you fine people may lead me to the solution.</p>
  
  <p>Thanks ever so for reading.</p>