image.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. public static function normalise($path, $max_width = 1920) {
  12. $size = getimagesize($path);
  13. list($width, $height) = $size;
  14. $exif = exif_read_data($path);
  15. $rotate_angle = 0;
  16. $is_flipped = false;
  17. if($exif !== false) {
  18. $orientation = $exif["Orientation"] ?? 0;
  19. if(in_array($orientation, [6, 5])) $rotate_angle = 270;
  20. if(in_array($orientation, [3, 4])) $rotate_angle = 180;
  21. if(in_array($orientation, [8, 7])) $rotate_angle = 90;
  22. if(in_array($orientation, [5, 4, 7])) $is_flipped = true;
  23. }
  24. $original_image = imagecreatefromjpeg($path);
  25. if($width > $height) {
  26. if($width > $max_width) {
  27. $width = $max_width;
  28. }
  29. }
  30. else {
  31. if($height > $max_width) {
  32. $ratio = $height / $max_width;
  33. $width = floor($width / $ratio);
  34. }
  35. }
  36. // Resize
  37. if($width != $size[0]) {
  38. $output_image = imagescale($original_image, $width, -1, IMG_BICUBIC);
  39. imagedestroy($original_image);
  40. }
  41. else {
  42. $output_image = $original_image;
  43. }
  44. // Rotate
  45. if($rotate_angle) {
  46. $output_image = imagerotate($output_image, $rotate_angle, 0);
  47. }
  48. // Flip
  49. if($is_flipped) {
  50. $output_image = imageflip($output_image, IMG_FLIP_HORIZONTAL);
  51. }
  52. return $output_image;
  53. }
  54. }