ConversorWebp.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. class ConversorWep {
  3. public static function generaImagenWebp($file, $compression_quality = 80) {
  4. $temp = explode('.', $file);
  5. $output_file = 'imgConvert/convertidas/' . $temp[0] . '.webp';
  6. $file = 'imgConvert/originales/' . $file;
  7. // check if file exists
  8. if (!file_exists($file)) {
  9. return false;
  10. }
  11. // If output file already exists return path
  12. if (file_exists($output_file)) {
  13. return $output_file;
  14. }
  15. $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  16. if (function_exists('imagewebp')) {
  17. switch ($file_type) {
  18. case 'jpeg':
  19. case 'jpg':
  20. $image = imagecreatefromjpeg($file);
  21. break;
  22. case 'png':
  23. $image = imagecreatefrompng($file);
  24. imagepalettetotruecolor($image);
  25. imagealphablending($image, true);
  26. imagesavealpha($image, true);
  27. break;
  28. case 'gif':
  29. $image = imagecreatefromgif($file);
  30. break;
  31. default:
  32. return false;
  33. }
  34. // Save the image
  35. $result = imagewebp($image, $output_file, $compression_quality);
  36. if (false === $result) {
  37. return false;
  38. }
  39. // Free up memory
  40. imagedestroy($image);
  41. return $output_file;
  42. } elseif (class_exists('Imagick')) {
  43. $image = new Imagick();
  44. $image->readImage($file);
  45. if ($file_type === 'png') {
  46. $image->setImageFormat('webp');
  47. $image->setImageCompressionQuality($compression_quality);
  48. $image->setOption('webp:lossless', 'true');
  49. }
  50. $image->writeImage($output_file);
  51. return $output_file;
  52. }
  53. return false;
  54. }
  55. }