Get image type from base64 encoded src string

WHAT I NEED

My src image is as follows

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

How can I extract the image type ie; jpeg from the above src. I use PHP, and the cacn image type is also png and gif.

+11
source share
10 answers

You have basically two options:

  • Trust metadata
  • Enter the image source directly.

Option 1:

Probably a faster way, because it only includes a separator string, but may be incorrect. Sort of:

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

Option 2:

Use getimagesize() and the equivalent for the string:

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

This is how I did it:

 $uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF......." $img = explode(',', $uri); $ini =substr($img[0], 11); $type = explode(';', $ini); echo $type[0]; // result png 
+5
source

Check 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)); 
+4
source
 $encoded_string = "...."; $imgdata = base64_decode($encoded_string); $f = finfo_open(); $mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE); 
+3
source

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

 function getMIMETYPE($base64string){ preg_match("/^data:(.*);base64/g",$base64string, $match); echo $match[1]; } 
+1
source

I hope this helps, but the right way to do it.

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

Please do not just use, data: image / png, since it is unreliable, I could easily fake this part and send you a base64 encoded .exe file.

+1
source

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

 $base64string = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...'; preg_match("/^data:image\/(.*);base64/i",$base64string, $match); $extension = $match[1]; 
0
source
 $str = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...'; $ext = end(explode('/', (explode(';', $str))[0])); 

Result: JPEG

0
source

This solution worked best for me, combining option 1 presented by Boris Gehry.

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

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

0
source
 $str64 = base64 string function base64Extension($str64) { return explode(";", explode("/", $str64)[1])[0]; } 
0
source

Source: https://habr.com/ru/post/953318/


All Articles