| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- class Image {
- // Takes an image and makes the largest dimension 1920 pixels large and rotates it according to EXIF data.
- public static function isJPEG($path) {
- $size = @getimagesize($path);
- if(!$size) return false;
- list(, , $type) = $size;
- if($type != IMAGETYPE_JPEG) return false;
- return true;
- }
- /**
- * @param string $path
- * @param int $max_width
- * @return bool|GdImage|resource
- * @throws Exception
- */
- public static function normalise(string $path, int $max_width = 1920) {
- $size = getimagesize($path);
- if($size === false) throw new Exception(__("Failed to determine image size."));
- [$image_width, $image_height] = $size;
- $exif = exif_read_data($path);
- $rotate_angle = 0;
- $is_flipped = false;
- if($exif !== false) {
- $orientation = $exif["Orientation"] ?? 0;
- if(in_array($orientation, [6, 5])) $rotate_angle = 270;
- if(in_array($orientation, [3, 4])) $rotate_angle = 180;
- if(in_array($orientation, [8, 7])) $rotate_angle = 90;
- if(in_array($orientation, [5, 4, 7])) $is_flipped = true;
- }
- $original_image = imagecreatefromjpeg($path);
- if($original_image === false) throw new Exception(__("Failed to load image."));
- // Horizontal images
- if($image_width > $image_height && $image_width > $max_width) {
- $target_width = $max_width;
- }
- // Vertical images
- else if($image_height > $max_width) {
- $ratio = $image_height / $max_width;
- $target_width = (int) floor($image_height / $ratio);
- }
- else {
- $target_width = $image_width;
- }
- // Resize
- if($image_width !== $target_width) {
- $output_image = imagescale($original_image, $target_width);
- if($output_image === false) throw new Exception(__("Failed to resize image."));
- imagedestroy($original_image);
- }
- else {
- $output_image = $original_image;
- }
- // Rotate
- if($rotate_angle) {
- $output_image = imagerotate($output_image, $rotate_angle, 0);
- if($output_image === false) throw new Exception(__("Failed to rotate image."));
- }
- // Flip
- if($is_flipped) {
- $output_image = imageflip($output_image, IMG_FLIP_HORIZONTAL);
- if($output_image === false) throw new Exception(__("Failed to flip image."));
- }
- return $output_image;
- }
- }
|