Skip to content

Instantly share code, notes, and snippets.

@hasinhayder
Created June 5, 2017 09:12
Show Gist options
  • Save hasinhayder/b2cfb0b026a3de059127904fcc8712ba to your computer and use it in GitHub Desktop.
Save hasinhayder/b2cfb0b026a3de059127904fcc8712ba to your computer and use it in GitHub Desktop.
Replace images with Dummy Placeholder Image
<?php
/* Keep your images in a folder named 'img' in the same folder where this script resides*/
/* Run the command "php imagereplace.php */
/* ImageMagick PHP extension is required */
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = $path;
} else if ($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
$images = getDirContents("./imgs");
foreach ($images as $image) {
if (strpos($image, ".jpg") !== false || strpos($image, ".png") !== false) {
generateDummyImages($image);
}
}
/**
*
* @param array $files
* @param string $dataOutPath
*/
function generateDummyImages($filename) {
$size = getimagesize($filename);
$width = $size[0];
$height = $size[1];
$imageCompressionQuality = 60;
$draw = new ImagickDraw();
$draw->pushPattern('typo', 0, 0, $width, $height);
/* Close the pattern */
$draw->popPattern();
$draw->setFillColor(new ImagickPixel("#888888"));
if ($width > 300) {
$draw->setFontSize(40);
$draw->annotation($width / 2 - 90, $height / 2, "{$width} x {$height}");
} else {
$draw->setFontSize(20);
$draw->annotation($width / 2 - 50, $height / 2, "{$width} x {$height}");
}
/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage($width, $height, new ImagickPixel("#cccccc"));
/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);
/* 1px black border around the image */
/* Set the format to PNG */
if (strpos($filename, "jpg") !== false) {
$canvas->setImageFormat('jpg');
$canvas->setImageCompression(Imagick::COMPRESSION_JPEG);
$canvas->setCompressionQuality($imageCompressionQuality);
} else if (strpos($filename, "png") !== false) {
$canvas->setImageFormat('png');
}
/* Output the image */
$canvas->writeimage($filename);
echo "Image generated: " . $filename . PHP_EOL;
//}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment