
Bạn có biết rằng việc tối ưu hóa hình ảnh có thể giúp website của bạn tải nhanh hơn và cải thiện trải nghiệm người dùng? Một trong những cách hiệu quả nhất là chuyển đổi hình ảnh sang định dạng WebP. Hãy cùng tìm hiểu cách thực hiện điều này nhé!
Lợi ích cụ thể
WebP giảm kích thước tệp trung bình 25-35% so với JPG/PNG, giúp tăng tốc độ tải trang, cải thiện SEO và tiết kiệm băng thông. Điều này đặc biệt hữu ích cho các website có nhiều hình ảnh như blog du lịch hay portfolio. Người dùng sẽ ít thoát trang hơn nhờ trải nghiệm mượt mà!
Hướng dẫn nhanh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
function ws_image_to_webp($file, $compression_quality = 100) { if (!file_exists($file)) return false; $file_type = exif_imagetype($file); $output_file = $file . '.webp'; if (file_exists($output_file)) return $output_file; if (function_exists('imagewebp')) { switch ($file_type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($file); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($file); imagepalettetotruecolor($image); imagealphablending($image, true); imagesavealpha($image, true); break; case IMAGETYPE_BMP: $image = imagecreatefrombmp($file); break; case IMAGETYPE_XBM: $image = imagecreatefromxbm($file); break; default: return false; } $result = imagewebp($image, $output_file, $compression_quality); if ($result === false) return false; imagedestroy($image); return $output_file; } elseif (class_exists('Imagick')) { $image = new Imagick(); $image->readImage($file); if ($file_type === IMAGETYPE_PNG) { $image->setImageFormat('webp'); $image->setImageCompressionQuality($compression_quality); $image->setOption('webp:lossless', 'true'); } $image->writeImage($output_file); return $output_file; } return false; } |
Lưu ý: khi sử dụng hàm convert này phải bắt buộc kích hoạt GD extentions
- Ở dưới local nếu sử dụng XAMPP thì config như sau

- Mở file php.ini và xóa dấu ‘;’ phía trước extension=gd để kích hoạt, code đúng sẽ như hình bên dưới
