Reputation: 21
How do I get the image type from a base64 string? I read another post similar to this but it doesn't give the image type, jpeg, png, etc. Below is my current code.
$type = finfo_buffer(finfo_open(), base64_decode($b64Img), FILEINFO_MIME_TYPE);
print($type);
//prints "application/octet-stream"
Upvotes: 2
Views: 7545
Reputation: 162
Once you have the base64 text of your image, you just need to analyze the first section of it to determine the file type. All base64 strings begin with something like this:
"data:image/(png|jpg|gif);base64,iVBORw0KG..."
You just have to look at the part between the image/
and the ;
and it will tell you the format.
Upvotes: -1
Reputation: 9429
You will need to decode the base64 data and then read the magic of it:
// read first 12 characters out of the base64 stream then decode
// to 9 characters. (9 should be sufficient for a magic)
$magic = base64_decode(substr($b64Img, 0, 12));
// determine file type
if (substr($magic, 0, 1) == 0xff &&
substr($magic, 1, 1) == 0xd8)
{
// jpg
}
else if (substr($magic, 0, 1) == 0x89 &&
substr($magic, 1, 5) == "PNG\r\n" &&
substr($magic, 6, 1) == 0x1a &&
substr($magic, 7, 1) == "\r")
{
// png
}
...
Upvotes: 0
Reputation: 101
Instead of FILEINFO_MIME you can also use FILEINFO_MIME_TYPE available since PHP 5.3.0.
Upvotes: 1
Reputation: 197564
This code should work, give it a try:
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer(base64_decode($b64Img)) . "\n";
Upvotes: 2