php - image resizing png adding black colour in background -
i resizing images using code below, problem resizing png images transparent background fills background black color.
below full code of image resizing:
function store_uploaded_image($html_element_name, $new_img_width, $new_img_height ,$size ,$target_dir) { $target_file = $target_dir .'image-'.$size.'.png'; $image = new simpleimage(); $image->load($_files[$html_element_name]['tmp_name']); $image->resize($new_img_width, $new_img_height); $image->save($target_file); return $target_file; //return name of saved file in case want store in database or show confirmation message user } class simpleimage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == imagetype_jpeg ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == imagetype_gif ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == imagetype_png ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=imagetype_png, $compression=75, $permissions=null) { if( $image_type == imagetype_jpeg ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == imagetype_gif ) { imagegif($this->image,$filename); } elseif( $image_type == imagetype_png ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=imagetype_jpeg) { if( $image_type == imagetype_jpeg ) { imagejpeg($this->image); } elseif( $image_type == imagetype_gif ) { imagegif($this->image); } elseif( $image_type == imagetype_png ) { imagepng($this->image); } } function getwidth() { return imagesx($this->image); } function getheight() { return imagesy($this->image); } function resizetoheight($height) { $ratio = $height / $this->getheight(); $width = $this->getwidth() * $ratio; $this->resize($width,$height); } function resizetowidth($width) { $ratio = $width / $this->getwidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getwidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getwidth(), $this->getheight()); $this->image = $new_image; } }
edit:
as @marc b suggested, using imagealphablending
, imagesavealpha
before imagecopyresampled
made work.
imagealphablending( $targetimage, false ); imagesavealpha( $targetimage, true );
Comments
Post a Comment