- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Environmental Science
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- articles and Answers
- Effective Resume Writing
- HR Interview articles
- Computer Glossary
- Who is Who
Convert png, jpg, jpeg, gif to webp using PHP Function
To convert PNG, JPG, JPEG, and GIF files to WebP format using PHP, you can use the GD library and imagewebp() function. Here's an example code snippet that should do the trick:
function convertToWebP($sourcePath, $destinationPath) {
// Check if the file is a supported image type
$mime = mime_content_type($sourcePath);
if ($mime == 'image/png') {
$image = imagecreatefrompng($sourcePath);
} elseif ($mime == 'image/jpg' || $mime == 'image/jpeg') {
$image = imagecreatefromjpeg($sourcePath);
} elseif ($mime == 'image/gif') {
$image = imagecreatefromgif($sourcePath);
} else {
return false;
}
// Convert the image to WebP and save it
imagewebp($image, $destinationPath, 80);
// Free up memory
imagedestroy($image);
return true;
}
// Example usage
convertToWebP('image.png', 'image.webp');
convertToWebP('photo.jpg', 'photo.webp');
convertToWebP('animation.gif', 'animation.webp');
Note that not all browsers support the WebP format, so you may want to consider providing fallback formats like PNG or JPEG in case the user's browser doesn't support WebP.
Advertisements
ads