1
0

image.php 1.5 KB

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