Is it possible to find out the type of an image encoded as a base64 String in PHP?
I have no method of accessing the original image file, just the encoded string. F
If you dont want to use these functions because of their dependencies you can use the first bytes of the data:
function getBytesFromHexString($hexdata)
{
for($count = 0; $count < strlen($hexdata); $count+=2)
$bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
return implode($bytes);
}
function getImageMimeType($imagedata)
{
$imagemimetypes = array(
"jpeg" => "FFD8",
"png" => "89504E470D0A1A0A",
"gif" => "474946",
"bmp" => "424D",
"tiff" => "4949",
"tiff" => "4D4D"
);
foreach ($imagemimetypes as $mime => $hexbytes)
{
$bytes = getBytesFromHexString($hexbytes);
if (substr($imagedata, 0, strlen($bytes)) == $bytes)
return $mime;
}
return NULL;
}
$encoded_string = "....";
$imgdata = base64_decode($encoded_string);
$mimetype = getImageMimeType($imgdata);