2011-09-21 193 views
1

如何從base64字符串獲取圖像類型?我讀了另一篇類似於此的帖子,但它沒有給出圖像類型,jpeg,png等等。下面是我當前的代碼。PHP:從base64字符串獲取圖像類型字符串

$type = finfo_buffer(finfo_open(), base64_decode($b64Img), FILEINFO_MIME_TYPE); 
print($type); 
//prints "application/octet-stream" 
+0

哪裏是'$ b64Img'分配的?它是如何分配的? –

+0

$ b64Img在代碼前面分配。它只是圖像的base64字符串表示形式 – Peter

+0

'$ b64Img'的值是什麼? – salathe

回答

2

此代碼應該工作,不妨一試:

$finfo = new finfo(FILEINFO_MIME); 
echo $finfo->buffer(base64_decode($b64Img)) . "\n"; 
+0

這打印出「application/octet-stream; charset = binary」 我正在查看該文件是否爲jpg,png,gif。感謝您的意見。 – Peter

+0

然後,你剛剛得到了一些二進制塊。 'finfo'在您從中獲取信息的文件緩衝區中找不到任何圖像類型。 – hakre

+1

有沒有辦法看看它的JPEG或不? – Peter

1

相反FILEINFO_MIME,你還可以使用可自FILEINFO_MIME_TYPE PHP 5.3.0。

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 
} 
... 
-1

一旦你有你的形象的BASE64文本,你只需要分析它的第一部分,以確定文件類型。所有的base64字符串的東西開頭是這樣的:

"data:image/(png|jpg|gif);base64,iVBORw0KG..."

你只需要看看image/;之間的部分,它會告訴你的格式。