Created
December 23, 2022 13:55
-
-
Save vidux/2c08aa9adb00d7a5b60eb1791982987a to your computer and use it in GitHub Desktop.
add watermark to images in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
// Set the directory containing the images | |
$dir = realpath(dirname(__FILE__)) . "/"; | |
// Scan the directory for image files | |
$files = scandir($dir); | |
$output_dir = $dir . "/output/"; | |
// Set the allowed file types | |
$file_types = array('jpg', 'jpeg', 'png'); | |
$watermark = imagecreatefrompng('/path/to/watermark.png'); | |
// Iterate through the list of files | |
foreach ($files as $file) { | |
try { | |
if (!is_file($file)) { | |
continue; | |
} | |
// Check if the file is an image | |
$image_type = exif_imagetype($dir . $file); | |
if ($image_type && in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), $file_types)) { | |
// Load the original image | |
$image = null; | |
// Load the original image using the appropriate function | |
if ($image_type == IMAGETYPE_JPEG) { | |
$image = imagecreatefromjpeg($dir . $file); | |
} elseif ($image_type == IMAGETYPE_PNG) { | |
$image = imagecreatefrompng($dir . $file); | |
} else { | |
continue; | |
} | |
$image_width = imagesx($image); | |
$image_height = imagesy($image); | |
// Get the dimensions of the watermark image | |
$watermark_width = imagesx($watermark); | |
$watermark_height = imagesy($watermark); | |
// Calculate the position of the watermark on the image | |
$dest_x = $image_width - $watermark_width -5; | |
$dest_y = $image_height - $watermark_height - 5; | |
// Copy the watermark onto the original image | |
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height); | |
// Save the watermarked image to the output directory | |
$UUID = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)); | |
imagejpeg($image, $output_dir . $UUID . ".jpg", 100); | |
// Destroy the image resources to free up memory | |
imagedestroy($image); | |
} | |
} catch (\Throwable $th) { | |
echo $file . "\n"; | |
} | |
} | |
imagedestroy($watermark); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment