Skip to content

Instantly share code, notes, and snippets.

@twesolowski
Created October 8, 2020 09:08
Show Gist options
  • Save twesolowski/720ab34af68f0112d0ee614044f4ee3e to your computer and use it in GitHub Desktop.
Save twesolowski/720ab34af68f0112d0ee614044f4ee3e to your computer and use it in GitHub Desktop.
Finds jpg and png files, creates webp files
<?php
if (!extension_loaded('gd') || !function_exists('gd_info')) {
die("Missing gd!\n");
}
$gd = gd_info();
if (!$gd["WebP Support"]){
die("webp not supported");
}
$foldersToIgnore = ['img/tmp'];
$files = glob("{,*/,*/*/,*/*/*/}*.{jpg,png}", GLOB_BRACE);
foreach($files as $file){
echo PHP_EOL;
echo $file;
$pathInfo = pathinfo($file);
if(isIgnored($file, $foldersToIgnore)){
echo "\t IGNORE";
continue;
}
$webpPath = $pathInfo['dirname'].DIRECTORY_SEPARATOR.$pathInfo['filename'].".webp";
if(file_exists($webpPath)){
echo "\t WEBP_EXISTS=".(filesize($webpPath)/1000)."KB";
}else{
echo "\t TODO";
if(convertImageToWebP($file, $webpPath )){
echo "\t DONE=".(filesize($webpPath)/1000)."KB";
}
}
}
echo PHP_EOL;
function isIgnored($folder, $foldersToIgnore)
{
$folder = rtrim($folder, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
foreach($foldersToIgnore as $ignore){
if(substr($folder, 0, strlen($ignore)) == $ignore ){
return true;
}
}
return false;
}
function convertImageToWebP($source, $destination, $quality = 80) {
$format = exif_imagetype ($source);
switch($format){
case 1:
$image = imagecreatefromgif($source);
break;
case 2:
$image = imagecreatefromjpeg($source);
break;
case 3:
$image = imagecreatefrompng($source);
break;
}
if($image){
return imagewebp($image, $destination , $quality);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment