我有一个从数据库中检索的base64图像字符串。$imageBase64Str
我需要从这个内容中提取mime并显示图像。下面的代码就是这样做的。
function imgMime($imgBytes){
if(is_null($imgBytes)){
return(false);
}
if(strlen($imgBytes)<12){
return(false);
}
$file = tmpfile();
if(!fwrite($file,$imgBytes,12)){
fclose($file);
return(false);
}
$path = stream_get_meta_data($file)['uri'];
$mimeCode=exif_imagetype($path);
fclose($file);
if(!$mimeCode){
return(false);
}
return(image_type_to_mime_type($mimeCode));
}
$imageBytes=base64_decode($imageBase64Str,true);
if(!$imageBytes){
throw new Exception("cannot decode image base64");
}
$imageMime=imgMime($imageBytes);
if(!$imageMime){
throw new Exception("cannot recognize image mime");
}
header('Content-type: '.$imageMime);
echo($imageBytes);
我在这个解决方案中遇到的问题是,它要求我将内容的前12个字节写入一个临时文件。我想知道是否有一种简单的方法可以避免这种情况,而不需要手动维护一组mimes。另外,我想避免调用外部程序(通过调用 exec
例如),这样我的代码就可以保持可移植性。
我希望能有一个类似的php函数 exif_imagetype_from_bytes
. 我的 imgMime
函数会更简单。
function imgMime($imgBytes){
if(is_null($imgBytes)){
return(false);
}
if(strlen($imgBytes)<12){
return(false);
}
$mimeCode=exif_imagetype($imgBytes);
if(!$mimeCode){
return(false);
}
return(image_type_to_mime_type($mimeCode));
}
$imageBytes=base64_decode($imageBase64Str,true);
if(!$imageBytes){
throw new Exception("cannot decode image base64");
}
$imageMime=imgMime($imageBytes);
if(!$imageMime){
throw new Exception("cannot recognize image mime");
}
header('Content-type: '.$imageMime);
echo($imageBytes);
非常感谢 @Kunal Raut 的回答,让我想到了下面的解决方案。
function imgMime($imgBytes){
if(is_null($imgBytes)){
return(false);
}
if(strlen($imgBytes)<12){
return(false);
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime=$finfo->buffer($imgBytes);
if(strncmp($mime, "image/", 6) != 0){
return(false);
}
return($mime);
}
$imageBytes=base64_decode($imageBase64Str,true);
if(!$imageBytes){
throw new Exception("cannot decode image base64");
}
$imageMime=imgMime($imageBytes);
if(!$imageMime){
throw new Exception("cannot recognize image mime");
}
header('Content-type: '.$imageMime);
echo($imageBytes);
这个解决方案比我想象的要优雅得多。
我在这个解决方案中遇到的问题是,它要求我将内容的前12个字节写入一个临时文件。我想知道是否有一种简单的方法可以避免这种情况,而不需要手动维护一组mimes。
这是因为你的这部分代码
if(!fwrite($file,$imgBytes,12)){
fclose($file);
return(false);
}
它让你在文件中写入至少12个字节的数据,然后让执行前进。if()
并解决你的第一个问题。
我希望有一个类似于exif_imagetype_from_bytes的php函数。我的imgMime函数就简单多了
是的,有这样一个函数,它可以返回你的类型的 base64_decoded 字符串。
finfo_buffer()
有关此功能的更多细节 点击这里.
功能的使用