Skip to content

Instantly share code, notes, and snippets.

@EionRobb
Created August 7, 2017 23:27
Show Gist options
  • Save EionRobb/8e0c76178522bc963c75caa6a77d3d37 to your computer and use it in GitHub Desktop.
Save EionRobb/8e0c76178522bc963c75caa6a77d3d37 to your computer and use it in GitHub Desktop.
<?php
function imagecreatefromstring_autorotate($data)
{
$img = imagecreatefromstring($data);
if (substr($data, 0, 3) == "\xFF\xD8\xFF" && ($data{3} == "\xDB" || $data{3} == "\xE0" || $data{3} == "\xE1")) {
$orientation = -1;
if (function_exists('exif_read_data')) {
$data_stream = preg_replace('@^data:@', 'data://', rawurlencode($data));
$exif = exif_read_data($data_stream);
if (isset($exif['Orientation']))
$orientation = $exif['Orientation'];
} else if (preg_match('@\x12\x01\x03\x00\x01\x00\x00\x00(.)\x00\x00\x00@', $data, $matches)) {
// Little endian EXIF
$orientation = ord($matches[1]);
} else if (preg_match('@\x01\x12\x00\x03\x00\x00\x00\x01\x00(.)\x00\x00@', $data, $matches)) {
// Big endian EXIF
$orientation = ord($matches[1]);
}
switch($orientation) {
case 2:
$img = imageflip($img, IMG_FLIP_HORIZONTAL);
break;
case 3:
$img = imagerotate($img, 180, 0);
break;
case 4:
$img = imageflip($img, IMG_FLIP_VERTICAL);
break;
case 5:
$img = imageflip($img, IMG_FLIP_VERTICAL);
// Fallthrough
case 6:
$img = imagerotate($img, -90, 0);
break;
case 7:
$img = imageflip($img, IMG_FLIP_VERTICAL);
// Fallthrough
case 8:
$img = imagerotate($img, 90, 0);
break;
}
}
return $img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment