如何從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