Get image type from base64 encoded src string

Well you have basically two options:

  1. Trust the metadata
  2. Type check the image source directly

Option 1:

Probably the quicker way because it only involve splitting string, but it may be incorrect. Something like:

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos  = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];

Option 2:

Use getimagesize() and it's equivalent for string:

$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype

Test this:

<?php

$str = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...';

function getB64Type($str) {
    // $str should start with 'data:' (= 5 characters long!)
    return substr($str, 5, strpos($str, ';')-5);
}
var_dump(getB64Type($str));

Tags:

Php

Image