/**
- * Add background
- * @param string $src Image path
- * @param int $w Background image width
- * @param int $h Background image height
- * @return Return the image with background
- * **/
- public function addBg($src,$w,$h)
- {
- $bg = imagecreatetruecolor($w,$h );
- $white = imagecolorallocate($bg,255,255,255);
- imagefill($bg,0,0,$white);//Fill the background
//Get the target image information
- $ info=getimagesize($src);
- $width=$info[0];//Target image width
- $height=$info[1];//Target image height
- switch ($info[2]){
- case 1:
- $img = imagecreatefromgif($src);
- break;
- case 2:
- $img = imagecreatefromjpeg($src);
- break;
- case 3:
- $img = imagecreatefrompng($src);
- break;
- default:
- exit('Unsupported image format');
- break;
- }
- if($height < $h)
- {
- $x=0;
- $y=($h-$height)/2 ;//Vertical centering
- }
- if($width < $w)
- {
- $x=($w-$width)/2;//Horizontal centering
- $y=0;
- }
- if($height < $h && $width < $w){
- $x = ($w-$width)/2;
- $y = ($h-$height)/2;
- }
- imagecopymerge($bg,$ img,$x,$y,0,0,$width,$height,100);
- imagejpeg($bg,$src,100);
- imagedestroy($bg);
- imagedestroy($img);
- return $ src;
- }
Copy code
|