1
0

image.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. class Image {
  3. // Takes an image and makes the largest dimension 1920 pixels large and rotates it according to EXIF data.
  4. public static function isJPEG($path) {
  5. $size = @getimagesize($path);
  6. if(!$size) return false;
  7. list(, , $type) = $size;
  8. if($type != IMAGETYPE_JPEG) return false;
  9. return true;
  10. }
  11. /**
  12. * @param string $path
  13. * @param int $max_width
  14. * @return bool|GdImage|resource
  15. * @throws Exception
  16. */
  17. public static function normalise(string $path, int $max_width = 1920) {
  18. $size = getimagesize($path);
  19. if($size === false) throw new Exception(__("Failed to determine image size."));
  20. [$image_width, $image_height] = $size;
  21. $exif = exif_read_data($path);
  22. $rotate_angle = 0;
  23. $is_flipped = false;
  24. if($exif !== false) {
  25. $orientation = $exif["Orientation"] ?? 0;
  26. if(in_array($orientation, [6, 5])) $rotate_angle = 270;
  27. if(in_array($orientation, [3, 4])) $rotate_angle = 180;
  28. if(in_array($orientation, [8, 7])) $rotate_angle = 90;
  29. if(in_array($orientation, [5, 4, 7])) $is_flipped = true;
  30. }
  31. $original_image = imagecreatefromjpeg($path);
  32. if($original_image === false) throw new Exception(__("Failed to load image."));
  33. // Horizontal images
  34. if($image_width > $image_height && $image_width > $max_width) {
  35. $target_width = $max_width;
  36. }
  37. // Vertical images
  38. else if($image_height > $max_width) {
  39. $ratio = $image_height / $max_width;
  40. $target_width = (int) floor($image_height / $ratio);
  41. }
  42. else {
  43. $target_width = $image_width;
  44. }
  45. // Resize
  46. if($image_width !== $target_width) {
  47. $output_image = imagescale($original_image, $target_width);
  48. if($output_image === false) throw new Exception(__("Failed to resize image."));
  49. imagedestroy($original_image);
  50. }
  51. else {
  52. $output_image = $original_image;
  53. }
  54. // Rotate
  55. if($rotate_angle) {
  56. $output_image = imagerotate($output_image, $rotate_angle, 0);
  57. if($output_image === false) throw new Exception(__("Failed to rotate image."));
  58. }
  59. // Flip
  60. if($is_flipped) {
  61. $output_image = imageflip($output_image, IMG_FLIP_HORIZONTAL);
  62. if($output_image === false) throw new Exception(__("Failed to flip image."));
  63. }
  64. return $output_image;
  65. }
  66. }