Get MIME type from encoded image in php

Get MIME type from encoded image in php
 
Get info from data: image Like: 
Example:$data_image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';

//$data_base64_encoded = Your encoded data: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA

$data_base64_encoded = $image_data; //$data_base64; 

//getting image extension:

$data_image = $data_base64_encoded;
$data_pos   = strpos($data_image, ';');
$data_type  = explode(':', substr($data_image, 0, $data_pos))[1];
$data_type_split = explode( '/', $data_type );
$data_extn = $data_type_split[1]; 


//get decoded image from encoded with mimetype:

$temp_data = str_replace('data:image/'.$data_extn.';base64,', '', $data_base64_encoded);

$temp_data = str_replace(' ', '+', $temp_data);
$data_base64_decoded = base64_decode($temp_data);

//new uploding file name:

$rand = (rand(10,10000));
$new_file_name  = time().$rand.'.'.$data_extn;
$new_file       = 'image/'.$new_file_name;

$new_success    = file_put_contents($new_file, $data_base64_decoded);

if($new_success){
   //successfully uploaded image
}
Please follow and like us: