Skip to content

Instantly share code, notes, and snippets.

@mikeyjk
Last active April 24, 2020 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeyjk/1c215fba3691567b994348ea956d23ea to your computer and use it in GitHub Desktop.
Save mikeyjk/1c215fba3691567b994348ea956d23ea to your computer and use it in GitHub Desktop.
given the raw contents of an image file, determine the mime type and file extension
<?
/**
* Given raw image data, return the file extension and MIME type of the file.
* The file extension includes the period character ('.').
*
* If the picture contents are invalid or corrupted, the values will be null.
*
* @param $picture
* @return array
* @see https://www.php.net/manual/en/function.getimagesizefromstring.php
* @see https://www.php.net/manual/en/function.getimagesize.php (for return specification)
* @see https://www.php.net/manual/en/function.image-type-to-extension.php
*/
public function getPictureMetadata($pictureContents) {
$metadata = getimagesizefromstring($pictureContents);
$mimeType = $metadata['mime'] ?? null;
return [
'extension' => $mimeType !== null ? image_type_to_extension($mimeType) : null,
'mime' => $mimeType
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment