Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting image type from base64 string in PHP

Is it possible to find out the type of an image encoded as a base64 String in 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.

like image 628
Epicurus Avatar asked May 19 '11 16:05

Epicurus


People also ask

How can I get image from base64 in PHP?

To get the image type you can do it like this : $split = explode( '/', $mime_type ); $type = $split[1]; In fact, (if you don't know it) the mime type for images is : image/type and type can be png or gif or jpeg or ... Hope that can help someone and thanks to @Marc B for his solution.

How do I know if an image is base64?

It is impossible to clearly distinguish text string and Base64 image encoding string. The only way - check if your string is valid Base 64 encoding string. If it is - probably it is an image. If not - you can be sure it is a text.

How do I get the extension of a base64 string?

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split . Then we get the first item from that. And, then we call split again to split the returned string by the / . Then we get the file extension by taking the 2nd element from the returned result.

What is a b64 file?

Binary file encoded using base64 encoding; often used to convert text data into base64 data; enables more reliable transmission of e-mail attachments and other information; similar to a . MIME attachment.


1 Answers

FileInfo can do that for you:

$encoded_string = "...."; $imgdata = base64_decode($encoded_string);  $f = finfo_open();  $mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE); 
like image 170
Marc B Avatar answered Sep 19 '22 09:09

Marc B