phpbase64image-formats

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.


Solution

  • 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);