Detecting image type from base64 string in PHP

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 dont want to use these functions because of their dependencies you can use the first bytes of the data:

function getBytesFromHexString($hexdata)
{
  for($count = 0; $count < strlen($hexdata); $count+=2)
    $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));

  return implode($bytes);
}

function getImageMimeType($imagedata)
{
  $imagemimetypes = array( 
    "jpeg" => "FFD8", 
    "png" => "89504E470D0A1A0A", 
    "gif" => "474946",
    "bmp" => "424D", 
    "tiff" => "4949",
    "tiff" => "4D4D"
  );

  foreach ($imagemimetypes as $mime => $hexbytes)
  {
    $bytes = getBytesFromHexString($hexbytes);
    if (substr($imagedata, 0, strlen($bytes)) == $bytes)
      return $mime;
  }

  return NULL;
}

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

The solution given by @Marc B is the best one for me (if our php version is > 5.3.0 otherwise we can use the solution given by @Aaron Murgatroyd).

I would like to give a little addition to this solution.

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.

For an exhaustive list of mime type you can look here :

  • http://www.sitepoint.com/web-foundations/mime-types-complete-list/