Created
May 3, 2018 06:02
-
-
Save Guley/ac15bb4f073e4f7dbc2eb2ade1b0cb50 to your computer and use it in GitHub Desktop.
PHP Base64 to image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$data = '/*Add you base64 encode data*/'; | |
$encoded_string = base64_encode($data); | |
if(!empty($encoded_string)){ | |
$imgdata = base64_decode($encoded_string); | |
$f = finfo_open(); | |
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE); | |
$img = 'data:'.$mime_type.';base64,'.$encoded_string; | |
$fileType = ''; | |
if($mime_type == 'image/jpeg'){ | |
$fileType = '.jpeg'; | |
}else if($mime_type == 'image/jpg'){ | |
$fileType = '.jpg'; | |
} | |
else if($mime_type == 'image/png'){ | |
$fileType = '.png'; | |
}else if($mime_type == 'image/JPG'){ | |
$fileType = '.JPG'; | |
}else if($mime_type == 'image/JPEG'){ | |
$fileType = '.JPEG'; | |
} | |
$img = str_replace('data:'.$mime_type.';base64,', '', $img); | |
$img = str_replace(' ', '+', $img); | |
//Now decode the image data using base64_decode function like below: | |
$img = base64_decode($img); | |
//Now you can put this image data to your desired file using file_put_contents function like below: | |
$filename='test'; | |
$file = $_SERVER["DOCUMENT_ROOT"].'images/'.$filename.$fileType; | |
$success = file_put_contents($file, $img); | |
return $success ? TRUE : FALSE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment