The key part starts from ob_end_clean(); in the following code snippet:

// Read background image and overlay image
$backgroundPath = 'background image path';
$overlayPath = 'overlay path';
// Get resources for background and overlay images
$background = imagecreatefrompng($backgroundPath);
$overlay = imagecreatefrompng($overlayPath);

// Get overlay image width and height
$overlayWidth = imagesx($overlay);
$overlayHeight = imagesy($overlay);

// Merge overlay onto background
imagecopy($background, $overlay, 0, 0, 0, 0, $overlayWidth, $overlayHeight);

// Create new true color image resource
$output = imagecreatetruecolor($overlayWidth, $overlayHeight);

// Copy merged image into output
imagecopy($output, $background, 0, 0, 0, 0, $overlayWidth, $overlayHeight);

ob_end_clean();
header("content-type:image/png");
ob_start();
imagejpeg($output);
$content = ob_get_contents();
ob_end_clean();
echo $content;
die;