从 PHP 中的 base64 字符串检测图像类型

2022-01-21 00:00:00 base64 php image-formats

是否可以在 PHP 中找出编码为 base64 字符串的图像的类型?

Is it possible to find out the type of an image encoded as a base64 String in PHP?

我没有访问原始图像文件的方法,只有编码字符串.据我所见, imagecreatefromstring() 可以从字符串表示创建图像资源(在从 base64 解码之后),但它会自动检测图像类型并且图像资源本身是特殊的PHP 表示.如果我想再次将图像另存为文件,我将不知道我将其保存为的类型是否对应于创建字符串表示的原始类型.

I have no method of accessing the original image file, just the encoded string. From what I've seen, imagecreatefromstring() can create an image resource from a string representation (after it's been decoded from base64), but it automatically detects the image type and the image resource itself is a special PHP representation. In case I want to save the image as a file again, I would have no idea if the type I am saving it as corresponds to the original type from which the String representation was created.

推荐答案

FileInfo可以做给你的:

$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

相关文章