Search code examples
phpimagemagick

get mime type and extension of image in variable or file without extension


I have telegram bot receiving a photo in webhook. I can download photo but not get file extension. How to get image extension and optionally mime-type from variable containing photo?


Solution

  • You can use the buffer method on an finfo instance to get the mime type of an arbitrary string blob if you don't want to write it to disk first:

    // Just a small image from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever
    $blob = base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
    
    $finfo = new finfo(FILEINFO_MIME);
    echo $finfo->buffer($blob) . "\n";
    
    // Result: image/gif; charset=binary
    

    Demo: https://3v4l.org/EJ95S