Skip to content

Instantly share code, notes, and snippets.

@TheExpertNoob
Created October 2, 2023 07:58
Show Gist options
  • Save TheExpertNoob/97c3ca006496189521b526f2c75d82fa to your computer and use it in GitHub Desktop.
Save TheExpertNoob/97c3ca006496189521b526f2c75d82fa to your computer and use it in GitHub Desktop.
PHP to add an overlay to a random bg image
<?php
// Get the requested image filename from the query parameter
if (isset($_GET['image'])) {
$requestedImage = $_GET['image'];
// Check if the requested image exists in the 'images' folder
$imagesDir = 'images/';
$requestedImagePath = $imagesDir . $requestedImage;
if (file_exists($requestedImagePath)) {
$randomImage = $requestedImagePath;
} else {
die('Requested image not found.');
}
} else {
// If no specific image is requested, select a random background image
$images = glob('images/*.{jpg,jpeg,png}', GLOB_BRACE);
if (empty($images)) {
die('No images found in the folder.');
}
$randomImage = $images[array_rand($images)];
}
// Load the selected background image
$imageInfo = pathinfo($randomImage);
$imageExtension = strtolower($imageInfo['extension']);
if ($imageExtension === 'jpg' || $imageExtension === 'jpeg') {
$bg = imagecreatefromjpeg($randomImage);
} elseif ($imageExtension === 'png') {
$bg = imagecreatefrompng($randomImage);
} else {
die('Unsupported image format.');
}
// Define the desired size (1280x720)
$newWidth = 1280;
$newHeight = 720;
// Create a new image with the desired size
$resizedBg = imagecreatetruecolor($newWidth, $newHeight);
// Resize and crop the original background image to fit the desired size
imagecopyresampled($resizedBg, $bg, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($bg), imagesy($bg));
// Load the overlay PNG image with transparency
$overlay = imagecreatefrompng('overlay.png');
// Get the dimensions of the overlay image
$overlay_width = imagesx($overlay);
$overlay_height = imagesy($overlay);
// Calculate the position to place the overlay image (you can adjust this)
$pos_x = 0;
$pos_y = 0;
// Merge the overlay image onto the resized background
imagecopy($resizedBg, $overlay, $pos_x, $pos_y, 0, 0, $overlay_width, $overlay_height);
// Set the content type to JPEG
header('Content-Type: image/jpeg');
// Output the resulting image as JPEG
imagejpeg($resizedBg);
// Free up memory
imagedestroy($bg);
imagedestroy($resizedBg);
imagedestroy($overlay);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment