PNG Transparency Resize with SimpleImage.php Class
Now have the transparency working for PNG but not gif. Here are the edits to the specific functions in case it will help someone else:
Save Function:
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { // do this or they'll all go to jpeg $image_type=$this->image_type; if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { // need this for transparent png to work imagealphablending($this->image, false); imagesavealpha($this->image,true); imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); }
}
Resize Function
function resize($width,$height,$forcesize='n') { /* optional. if file is smaller, do not resize. */ if ($forcesize == 'n') { if ($width > $this->getWidth() && $height > $this->getHeight()){ $width = $this->getWidth(); $height = $this->getHeight(); } } $new_image = imagecreatetruecolor($width, $height); /* Check if this image is PNG or GIF, then set if Transparent*/ if(($this->image_type == IMAGETYPE_GIF) || ($this->image_type==IMAGETYPE_PNG)){ imagealphablending($new_image, false); imagesavealpha($new_image,true); $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127); imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent); } imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image;
}
The function imagecreatetruecolor()
does not work with GIF's. Use the imagecreate
method instead:
if($this->image_type == IMAGETYPE_GIF){ $new_image = imagecreate( $Width, $Height ); // for gif files} else{ $new_image = imagecreatetruecolor($Width, $Height); // for all other files}
I haven't been playing with GD for a long time myself (I prefer Imagemagick), but you could try setting alpha also to the source image before copying:
...// ADDED CODE IS HERE ..imagealphablending($this->image, true);...
HTH.