23

WHAT I REQUIRE

My image src looks like this

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...

How can I extract the image type ie; jpeg from the above src given. I am using PHP and the image type can also be png/gif/jpg.

YDF
  • 365
  • 5
  • 9
Developer
  • 1,030
  • 6
  • 14
  • 37
  • 2
    A bit of [Research](http://stackoverflow.com/questions/6061505/detecting-image-type-from-base64-string-in-php) – Patsy Issa Sep 06 '13 at 13:01
  • 1
    the most important and missing part on that "research" is that nowhere it is explained that the actual image is what comes after the coma, the base64_decode will not work -properly- with the part before the comma – Cesc May 21 '20 at 13:49

16 Answers16

27

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
Boris Guéry
  • 47,316
  • 8
  • 52
  • 87
  • 1
    it gives error getimagesizefromstring() expects parameter 1 to be string, array given – Developer Sep 06 '13 at 13:15
  • @Developer, fixed it missed getting index 1 of the resulting explode function :) – Boris Guéry Sep 06 '13 at 14:29
  • the two options have php error. With php i can't use [1] – Gino Feb 14 '14 at 18:12
  • can you tell me how exactly you fixed this? I got the exact same error by copying and pasting your code @BorisGuéry – user3531149 May 13 '14 at 13:30
  • @user3531149, it is a shortcut notation since PHP5.5, you're probably using an older version. Just set the result of the function to a variable and access the array values from there. – Boris Guéry May 13 '14 at 13:34
  • I recently installed php5.5 just for this snippet sir, but it still throws this error :/ – user3531149 May 13 '14 at 13:35
  • @Boris Guéry, You should remove Option 2 really. It doesnt work and just confuses. I am using PHP 7, it has nothing to do with versions of php. `base64_decode($data)` returns boolean `false` which gives error on exploding. So please remove this Option2. – Abhay Maurya Jan 13 '17 at 11:59
  • Option 1 will give the "image/" as a prefix to the image Type. So to remove that add following code in the next line- $type = str_replace('image/', "", $type); – Jitendra Nov 26 '18 at 13:02
  • 1
    Option 2 is just "almost" but wrong. It should be like this: getimagesizefromstring( base64_decode(explode(",",$data)[1])); the "explode" has to be inside the base64 not the other way around, you want to decode base64 whats after the "," . That way written here in this solution just breaks – Cesc May 21 '20 at 14:00
10

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));
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • Why minus 5 here? – Sagar Guhe Nov 07 '17 at 06:32
  • @SagarGuhe The [definition of substr](http://php.net/substr) is `substr($str, $start [, $length])`. The starting point is the sixth character, i.e. after the colon (= 5 characters). The desired substring goes until `;`, the length from `:` (exclusive) to `;` (exclusive) is index of `;` minus the position of `:`. – ComFreek Nov 07 '17 at 08:29
8

I hope this helps but the correct way to do this is.

$uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF......."
$encodedImgString = explode(',', $uri, 2)[1];
$decodedImgString = base64_decode($encodedImgString);
$info = getimagesizefromstring($decodedImgString);

echo $info['mime'];

Please don't just use the, data:image/png as that is not reliable, I could easily fake that part and send you a base64 encoded .exe file.

Matthew A Thomas
  • 924
  • 7
  • 15
7

This is the way that i made:

$uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF......."
$img = explode(',', $uri);
$ini =substr($img[0], 11);
$type = explode(';', $ini);
echo $type[0]; // result png
Tiago Mendes
  • 4,572
  • 1
  • 29
  • 35
4
$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);    
3

You can use this, if you use ajax to upload images then you will not get the correct MIME using finfo_buffer

function getMIMETYPE($base64string){
    preg_match("/^data:(.*);base64/g",$base64string, $match);
    echo $match[1];
}
Imal Hasaranga Perera
  • 9,683
  • 3
  • 51
  • 41
3
$str64 = base64 string

function base64Extension($str64) {
  return explode(";", explode("/", $str64)[1])[0];
}
Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
2

Use below regex code, it returns the extension of a file.

$base64string = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...';
preg_match("/^data:image\/(.*);base64/i",$base64string, $match);
$extension = $match[1];
Sled
  • 18,541
  • 27
  • 119
  • 168
suman
  • 68
  • 4
2
$str = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...';
$ext = end(explode('/', (explode(';', $str))[0]));

Result: jpeg

Adam Pery
  • 1,924
  • 22
  • 21
0

This solution worked best for me, piggybacking off of Option 1 presented by Boris Guery.

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

In this instance the solution returns jpeg file extension, in the $type variable.

0
String[] strings = base64String.split(",");
String extension;
switch (strings[0]) {//check image's extension
    case "data:image/jpeg;base64":
        extension = "jpeg";
        break;
    case "data:image/png;base64":
        extension = "png";
        break;
    default://should write cases for more images types
        extension = "jpg";
        break;
}
Suman
  • 74
  • 4
0

$type will return "data:image/jpeg"

then $extension returns "jpeg"

  $type      = explode(';', $httpFileRequest)[0];
  $extension = explode('/', $type)[1];
0

This is how I do:

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

function getMimeType($string)
{
    $string = explode(
        ';base64,',
        stristr($string, ';base64,', true)
    );

    if(empty($string[0])){
        return false;
    }

    preg_match('/^data:(.*)\/(.*)/', $string[0], $match);

    return [
        'type' => $match[1],
        'extension' => $match[2],
    ];
}

var_dump(
    getMimeType($string)
);
// array(2) { ["type"]=> string(5) "image" ["extension"]=> string(4) "jpeg" }
// array(2) { ["type"]=> string(5) "video" ["extension"]=> string(3) "mp4" }
Sinan Eldem
  • 5,564
  • 3
  • 36
  • 37
0

Best Way to get base64 image file type

    $type = explode('/', mime_content_type($base64_string))[1];
kishan maru
  • 31
  • 1
  • 3
  • 8
0

It's works for me and it's the best way to get base64 image file type. it only returns file extenstion like 'png', 'jpg', etc

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

return : jpeg

Mdr Kuchhadiya
  • 431
  • 4
  • 12
-1

This is best solution worked for me...

$str = "data:image/jpg;base64,R0lGODlhPQBEAPeoAJow==";
$name = time() . '.' . explode('/', explode(':', substr($str, 0, strpos(str, ';')))[1])[1];

Result: 1564650041.jpg