Created
February 4, 2023 09:18
-
-
Save alekstar79/190272310f3e4c809e2af85f38cb1947 to your computer and use it in GitHub Desktop.
Converting images to WebP 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
function convertToWebp(string $src, int $quality = 100): string | |
{ | |
$dir = pathinfo($src, PATHINFO_DIRNAME); | |
$name = pathinfo($src, PATHINFO_FILENAME); | |
$ext = pathinfo($src, PATHINFO_EXTENSION); | |
$dest = "$dir/{$name}_$ext.webp"; | |
$is_alpha = false; | |
switch (mime_content_type($src)) { | |
case 'image/png': | |
$img = imagecreatefrompng($src); | |
$is_alpha = true; | |
break; | |
case 'image/jpeg': | |
$img = imagecreatefromjpeg($src); | |
break; | |
default: | |
return $src; | |
} | |
if ($is_alpha) { | |
imagepalettetotruecolor($img); | |
imagealphablending($img, true); | |
imagesavealpha($img, true); | |
} | |
imagewebp($img, $dest, $quality); | |
return $dest; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment