How can imagecreatefrompng be used effectively to add a background image in PHP?

To add a background image using imagecreatefrompng in PHP, you can create a new image with the desired dimensions, load the background image using imagecreatefrompng, and then copy the background image onto the new image using imagecopy. Finally, you can save or output the new image as needed.

// Create a new image with desired dimensions
$newImage = imagecreatetruecolor($width, $height);

// Load the background image
$background = imagecreatefrompng('background.png');

// Copy the background image onto the new image
imagecopy($newImage, $background, 0, 0, 0, 0, $width, $height);

// Output the new image
header('Content-Type: image/png');
imagepng($newImage);

// Free up memory
imagedestroy($newImage);
imagedestroy($background);