PHP picture background filling example

WBOY
Release: 2016-07-25 08:53:44
Original
1856 people have browsed it
  1. /**

  2. * Add background
  3. * @param string $src Image path
  4. * @param int $w Background image width
  5. * @param int $h Background image height
  6. * @return Return the image with background
  7. * **/
  8. public function addBg($src,$w,$h)
  9. {
  10. $bg = imagecreatetruecolor($w,$h );
  11. $white = imagecolorallocate($bg,255,255,255);
  12. imagefill($bg,0,0,$white);//Fill the background

  13. //Get the target image information

  14. $ info=getimagesize($src);
  15. $width=$info[0];//Target image width
  16. $height=$info[1];//Target image height
  17. switch ($info[2]){
  18. case 1:
  19. $img = imagecreatefromgif($src);
  20. break;
  21. case 2:
  22. $img = imagecreatefromjpeg($src);
  23. break;
  24. case 3:
  25. $img = imagecreatefrompng($src);
  26. break;
  27. default:
  28. exit('Unsupported image format');
  29. break;
  30. }
  31. if($height < $h)
  32. {
  33. $x=0;
  34. $y=($h-$height)/2 ;//Vertical centering
  35. }
  36. if($width < $w)
  37. {
  38. $x=($w-$width)/2;//Horizontal centering
  39. $y=0;
  40. }
  41. if($height < $h && $width < $w){
  42. $x = ($w-$width)/2;
  43. $y = ($h-$height)/2;
  44. }
  45. imagecopymerge($bg,$ img,$x,$y,0,0,$width,$height,100);
  46. imagejpeg($bg,$src,100);
  47. imagedestroy($bg);
  48. imagedestroy($img);
  49. return $ src;
  50. }

Copy code


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template