image.php 1.3 KB

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