如何从base64字符串获取图像类型?我读了另一篇类似于此的帖子,但它没有给出图像类型,jpeg,png等等。下面是我当前的代码。PHP:从base64字符串获取图像类型字符串
$type = finfo_buffer(finfo_open(), base64_decode($b64Img), FILEINFO_MIME_TYPE);
print($type);
//prints "application/octet-stream"
如何从base64字符串获取图像类型?我读了另一篇类似于此的帖子,但它没有给出图像类型,jpeg,png等等。下面是我当前的代码。PHP:从base64字符串获取图像类型字符串
$type = finfo_buffer(finfo_open(), base64_decode($b64Img), FILEINFO_MIME_TYPE);
print($type);
//prints "application/octet-stream"
相反FILEINFO_MIME,你还可以使用可自FILEINFO_MIME_TYPE PHP 5.3.0。
您将需要解码的base64数据,然后读出它的神奇:
// 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
}
...
一旦你有你的形象的BASE64文本,你只需要分析它的第一部分,以确定文件类型。所有的base64字符串的东西开头是这样的:
"data:image/(png|jpg|gif);base64,iVBORw0KG..."
你只需要看看image/
和;
之间的部分,它会告诉你的格式。
哪里是'$ b64Img'分配的?它是如何分配的? –
$ b64Img在代码前面分配。它只是图像的base64字符串表示形式 – Peter
'$ b64Img'的值是什么? – salathe