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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With