Php image background filling instance

Source: Internet
Author: User
Php image background filling instance

  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 returns the image with the background added.
  7. ***/
  8. Public function addBg ($ src, $ w, $ h)
  9. {
  10. $ Bg = imagecreatetruecolor ($ w, $ h );
  11. $ White = imagecolorallocate ($ bg, 255,255,255 );
  12. Imagefill ($ bg, $ white); // fill the background

  13. // Obtain 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; // center vertically
  35. }
  36. If ($ width <$ w)
  37. {
  38. $ X = ($ w-$ width)/2; // horizontally centered
  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, 100, $ width, $ height );
  46. Imagejpeg ($ bg, $ src, 100 );
  47. Imagedestroy ($ bg );
  48. Imagedestroy ($ img );
  49. Return $ src;
  50. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.