Skip to content

Instantly share code, notes, and snippets.

@Arifursdev
Last active February 6, 2023 13:57
Show Gist options
  • Save Arifursdev/d4c1f95c6b4d740ca190fc4c6c7638f1 to your computer and use it in GitHub Desktop.
Save Arifursdev/d4c1f95c6b4d740ca190fc4c6c7638f1 to your computer and use it in GitHub Desktop.
<?php
function convertToWebp($imagePath) {
if(!file_exists($imagePath)) {
return false;
}
$info = getimagesize($imagePath);
$format = strtolower(substr($info['mime'], strpos($info['mime'], '/') + 1));
$image = null;
if ($format == 'jpeg') {
$image = imagecreatefromjpeg($imagePath);
} elseif ($format == 'png') {
$image = imagecreatefrompng($imagePath);
}
if (!$image) {
return false;
}
$webpImagePath = preg_replace('/\.(jpeg|jpg|png)$/', '.webp', $imagePath);
return imagewebp($image, $webpImagePath);
}
convertToWebp(__DIR__ . '/img.jpg');
convertToWebp(__DIR__ . '/image.jpg');
convertToWebp(__DIR__ . '/image.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment