Created
December 6, 2020 09:47
-
-
Save mix5003/0d16724b68a49efcda0e7e76455496ba to your computer and use it in GitHub Desktop.
Script for convert images to WebP
This file contains hidden or 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 | |
| function convertDir($path){ | |
| // echo "Search In $path\n"; | |
| $items = scandir($path); | |
| foreach($items as $item){ | |
| if($item === '.' || $item === '..'){ | |
| continue; | |
| } | |
| $itemPath = $path.'/'.$item; | |
| if(is_dir($itemPath)){ | |
| convertDir($itemPath); | |
| }else{ | |
| $extention = strtolower(substr($item, -4)); | |
| if($extention === '.jpg' || $extention === 'jpeg' || $extention === '.png'){ | |
| convertToWebP($itemPath); | |
| } | |
| } | |
| } | |
| } | |
| function convertToWebP($file){ | |
| $outputFile = $file.'.webp'; | |
| if(!file_exists($outputFile) || filectime($outputFile) < filectime($file)){ | |
| echo "Convert $file\n"; | |
| system ('cwebp "'.$file.'" -o "'.$outputFile.'" > /dev/null 2>&1'); | |
| } | |
| // echo ('cwebp "'.$file.'" -o "'.$file.'.webp"'."\n"); | |
| } | |
| $images = convertDir('.'); | |
| echo "Completed\n"; |
This file contains hidden or 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
| # Modified from https://wordpress.org/plugins/webp-express/#%0Ai%20am%20on%20nginx%20or%20openresty%0A | |
| location ~* .*\.(png|jpe?g)$ { | |
| try_files $uri; | |
| add_header Vary Accept; | |
| add_header Handle WebP; | |
| expires 365d; | |
| if ($http_accept ~* "webp"){ | |
| set $whattodo A; | |
| } | |
| if (-f $request_filename.webp) { | |
| set $whattodo "${whattodo}B"; | |
| } | |
| if ($whattodo = AB) { | |
| rewrite ^(.*) $1.webp last; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment