How to insert image over image in gd library in php?

Member

by jerad , in category: PHP General , 4 months ago

How to insert image over image in gd library in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 4 months ago

@jerad 

To insert an image over another image using the GD library in PHP, you can follow these steps:

  1. Load the base image using the imagecreatefromjpeg(), imagecreatefrompng(), or imagecreatefromgif() function based on the image format.
1
$baseImage = imagecreatefromjpeg('path/to/base/image.jpg');


  1. Load the overlay image using the same functions as step 1.
1
$overlayImage = imagecreatefromjpeg('path/to/overlay/image.jpg');


  1. Get the dimensions of the overlay image using the imagesx() and imagesy() functions:
1
2
$overlayWidth = imagesx($overlayImage);
$overlayHeight = imagesy($overlayImage);


  1. Calculate the position where the overlay image will be placed on the base image:
1
2
$positionX = 10; // customize this value according to your requirement
$positionY = 10; // customize this value according to your requirement


  1. Use the imagecopyresampled() function to merge the overlay image onto the base image:
1
imagecopyresampled($baseImage, $overlayImage, $positionX, $positionY, 0, 0, $overlayWidth, $overlayHeight, $overlayWidth, $overlayHeight);


  1. Finally, output or save the modified image using the imagejpeg(), imagepng(), or imagegif() functions:
1
2
header('Content-Type: image/jpeg'); // If you want to output the image directly
imagejpeg($baseImage, 'path/to/output/image.jpg'); // If you want to save the image


Remember to adjust the file paths and coordinates according to your specific needs.