Last active
May 4, 2024 14:01
-
-
Save lutzissler/2574727ac99375ed5c5637d6566d1e19 to your computer and use it in GitHub Desktop.
Get image size in PHP respecting EXIF rotation and handling SVG images.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function my_getimagesize($filename) { | |
$size = @getimagesize($filename); | |
if (is_array($size)) { | |
if (function_exists('exif_read_data')) { | |
$exif = @exif_read_data($filename); | |
if (is_array($exif) && isset($exif['Orientation']) && ($exif['Orientation'] == 6 || $exif['Orientation'] == 8)) { | |
// The image is tilted clockwise or counter-clockwise | |
// Flip width and height | |
$x = $size[0]; | |
$size[0] = $size[1]; | |
$size[1] = $x; | |
} | |
} | |
} else { | |
// Probably an SVG | |
$fh = @fopen($filename, 'r'); | |
if ($fh) { | |
$x = @fread($fh, 5); | |
if ($x === '<?xml') { | |
// This seems to be an XML file, dig deeper | |
$prev = $x; | |
do { | |
$x = @fread($fh, 512); | |
if ($x) { | |
$s = $prev . $x; | |
if (strpos($s, '<svg ') !== false || strpos($s, '<svg>') !== false) { | |
// This is an SVG | |
$size = array( | |
2 => 'SVG', | |
); | |
if (preg_match('/<svg[^>]+viewBox="\s*([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s*"/', $s, $matches)) { | |
$size[0] = $matches[3]; | |
$size[1] = $matches[4]; | |
} | |
} | |
$prev = $x; | |
} | |
} while (!$size && $x && !feof($fh)); | |
@fclose($fh); | |
} | |
} | |
} | |
return $size; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment