Skip to content

Instantly share code, notes, and snippets.

@BARNZ
Created December 2, 2017 04:28
Show Gist options
  • Save BARNZ/c5f24413014e2e71f7b7c07e6eb2cb45 to your computer and use it in GitHub Desktop.
Save BARNZ/c5f24413014e2e71f7b7c07e6eb2cb45 to your computer and use it in GitHub Desktop.
Auto-rotate image based on EXIF data
const EXIF_ROTATION_0 = 1;
const EXIF_MIRROR_0 = 2;
const EXIF_ROTATION_90 = 6;
const EXIF_MIRROR_90 = 5;
const EXIF_ROTATION_180 = 3;
const EXIF_MIRROR_180 = 4;
const EXIF_ROTATION_270 = 8;
const EXIF_MIRROR_270 = 7;
const GIF_TYPE = 1;
const JPG_TYPE = 2;
const PNG_TYPE = 3;
public static function adjustImageOrientation($filename, $quality = 90)
{
try {
$exif = @exif_read_data($filename);
} catch (\Exception $e) {
$exif = false;
}
// If no exif info, or no orientation info, or if orientation needs no adjustment
$orientation = array_get($exif, 'Orientation');
if (!$orientation || $orientation === self::EXIF_ROTATION_0) {
return false;
}
switch ($fileType = @exif_imagetype($filename)) {
case self::GIF_TYPE: // gif
$img = @imageCreateFromGif($filename);
break;
case self::JPG_TYPE: // jpg
$img = @imageCreateFromJpeg($filename);
break;
case self::PNG_TYPE: // png
$img = @imageCreateFromPng($filename);
break;
default:
$img = @imagecreatefromjpeg($filename);
}
if (!$img) {
return false;
}
$mirror = in_array($orientation, [self::EXIF_MIRROR_0, self::EXIF_MIRROR_90, self::EXIF_MIRROR_180, self::EXIF_MIRROR_270]);
$deg = 0;
switch ($orientation) {
case self::EXIF_ROTATION_180:
case self::EXIF_MIRROR_180:
$deg = 180;
break;
case self::EXIF_ROTATION_90:
case self::EXIF_MIRROR_90:
$deg = 270;
break;
case self::EXIF_ROTATION_270:
case self::EXIF_MIRROR_270:
$deg = 90;
break;
}
if ($deg) {
$img = imagerotate($img, $deg, 0);
}
if ($mirror) {
$img = imageflip($img, IMG_FLIP_HORIZONTAL);
}
switch ($fileType = @exif_imagetype($filename)) {
case self::GIF_TYPE: // gif
imagegif($img, $filename);
break;
case self::JPG_TYPE: // jpg
imagejpeg($img, $filename, $quality);
break;
case self::PNG_TYPE: // png
imagepng($img, $filename, $quality);
break;
default:
imagejpeg($img, $filename, $quality);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment