Utilities::transparentImage PHP Method

transparentImage() static public method

see http://stackoverflow.com/questions/279236/how-do-i-resize-pngs-with-transparency-in-php#279310
static public transparentImage ( integer $width, integer $height ) : image
$width integer
$height integer
return image
    static function transparentImage($width, $height)
    {
        $img = imagecreatetruecolor($width, $height);
        imagealphablending($img, false);
        imagesavealpha($img, true);
        $backgr = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefilledrectangle($img, 0, 0, $width, $height, $backgr);
        return $img;
    }

Usage Example

Example #1
0
 /**
  * Create a square thumbnail by stuffing the cover at the edges
  * @param  string $cover      path to book cover image
  * @param  int 	 	$newwidth   required thumbnail width
  * @param  int 		$newheight  required thumbnail height
  * @param  string $thumb_path path for thumbnail storage
  * @return bool             	true = thumbnail created
  */
 private function thumbnailStuffed($cover, $newwidth, $newheight, $thumb_path)
 {
     list($width, $height) = getimagesize($cover);
     $thumb = Utilities::transparentImage($newwidth, $newheight);
     $source = imagecreatefromjpeg($cover);
     $dstx = 0;
     $dsty = 0;
     $maxwh = max(array($width, $height));
     if ($height > $width) {
         $diff = $maxwh - $width;
         $dstx = (int) $diff / 2;
     } else {
         $diff = $maxwh - $height;
         $dsty = (int) $diff / 2;
     }
     $inbetween = $this->transparentImage($maxwh, $maxwh);
     imagecopy($inbetween, $source, $dstx, $dsty, 0, 0, $width, $height);
     imagecopyresampled($thumb, $inbetween, 0, 0, 0, 0, $newwidth, $newheight, $maxwh, $maxwh);
     $created = imagepng($thumb, $thumb_path);
     imagedestroy($thumb);
     imagedestroy($inbetween);
     imagedestroy($source);
     return $created;
 }