title: PHP GD Triangle Image Crop
body: <p>I've  noticed there's a few scripts about to try and do this, however none quite fi tmy situation.</p>
  
  <p>I've scraped together a few scripts I found to try and come up with the correct solution.</p>
  
  <p>However I've come across 2 problems now.</p>
  
  <ol>
  <li>The image isn't centered.</li>
  <li>The triangle doesn't have equal side lengths.</li>
  </ol>
  
  <p>The demo is at <a href="http://owenmelbourne.com/triangle.php" rel="nofollow">http://owenmelbourne.com/triangle.php</a></p>
  
  <p>the code is</p>
  
  <p>
  
  <pre><code>$src = imagecreatefromjpeg ('http://uat.eruptedevents.secureping.co.uk/media/images/upload/1200/154.jpg');
  // Get image width/height
  
  $srcWidth   = imagesx ($src);
  $srcHeight  = imagesy ($src);
  
  // Get centre position
  
  $centreX    = floor ($srcWidth / 2);
  $centreY    = floor ($srcHeight / 2);
  
  // Set new image size and start x/y
  
  $destWidth  = $srcWidth;
  $destHeight = $srcHeight;
  
  $destSX     = 0;
  $destSY     = $centreY;
  
  // Create the image
  $square = 500;
  
  if( $srcWidth &gt;= $srcHeight ){
      $square = $srcHeight;
  }
  else {
      $square = $srcWidth;
  }
  $shift = array ("left" =&gt; 0, "top" =&gt; 0);
  
  $shift["left"] = ( $srcWidth / 4 ) * -1;
  $shift["top"] = ( $srcHeight / 4 ) * -1;
  
  $dest   = imagecreatetruecolor ($square, $square);
  
  // Copy from source
  imagecopy ($dest, $src, $shift["left"], $shift["top"], 0, 0, $destWidth, $destHeight);
  
  // OK... we now have the correctly sized rectangle copied over from the source image
  // Lets cut it down and turn it into the triangle we want by removing the other triangles
  // We remove the area by defining another colour as transparent and creating shapes with that colour
  
  $colRed  = imagecolorallocatealpha ($dest, 255, 0, 0, 0);
  $blue  = imagecolorallocatealpha ($dest, 0, 0, 244, 0);
  imagecolortransparent ($dest, $colRed);
  
  $sidelength = $square;
  
  imagefilledpolygon ($dest, array (
                      0, 0,
                      $square/2, 0,
                      0, $square
                      ), 3, $colRed);
  imagefilledpolygon ($dest, array (
                      $square, 0,
                      $square, $square,
                      $square/2, 0
                      ), 3, $colRed);
  
  $dest2   = imagecreatetruecolor ($square, $square);
  
  // Output new image
  
  header ('Content-Type: image/png');
  imagepng ($dest);
  
  // Clean up
  
  imagedestroy ($thumbNail);
  imagedestroy ($dest);
  </code></pre>
  
  <p>How would I go about taking a perfect triangle crop from the middle, and returning it as the image?</p>
  
  <p>Many thanks</p>