Php image background filling instance
-
/**
- * Add background
- * @ Param string $ src Image path
- * @ Param int $ w background image width
- * @ Param int $ h background image height
- * @ Return returns the image with the background added.
- ***/
- Public function addBg ($ src, $ w, $ h)
- {
- $ Bg = imagecreatetruecolor ($ w, $ h );
- $ White = imagecolorallocate ($ bg, 255,255,255 );
- Imagefill ($ bg, $ white); // fill the background
-
// Obtain 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; // center vertically
- }
- If ($ width <$ w)
- {
- $ X = ($ w-$ width)/2; // horizontally centered
- $ Y = 0;
- }
- If ($ height <$ h & $ width <$ w ){
- $ X = ($ w-$ width)/2;
- $ Y = ($ h-$ height)/2;
- }
- Imagecopymerge ($ bg, $ img, $ x, $ y, 100, $ width, $ height );
- Imagejpeg ($ bg, $ src, 100 );
- Imagedestroy ($ bg );
- Imagedestroy ($ img );
- Return $ src;
- }
|