Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert base64 to image and validation helpers
function base64ToImage($imageData, $path){
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $imageData) = explode(';', $imageData);
list(,$extension) = explode('/',$type);
list(,$imageData) = explode(',', $imageData);
$fileName = uniqid().'.'.$extension;
$imageData = base64_decode($imageData);
file_put_contents($path."/".$fileName, $imageData);
return $fileName;
}
function isBase64($data = ""){
@list($type, $source) = explode("base64,", $data);
if (!$source || !$type) {
return false;
}
if ( base64_encode(base64_decode($source)) === $source){
return true;
} else {
return false;
}
}
function isImage($data){
$uri = substr($data, 5);
$dimension = @getimagesize($data);
$width = count($dimension) > 0 ? $dimension[0] : 0;
$height = count($dimension) > 0 ? $dimension[1] : 0;
list($type, $imageData) = explode(';base64,', $uri);
list(,$extension) = explode('/',$type);
$size = (int) (strlen(rtrim($imageData, '=')) * 3 / 4);
$extension = $extension == "jpg" ? "jpeg" : $extension;
if(function_exists($create="imagecreatefrom".$extension)){
if($create($data))
return true;
else
return false;
}else{
return false;
}
}
function smallerThan($data, $size){
$uri = substr($data, 5);
list($type, $imageData) = explode(';base64,', $uri);
list(,$extension) = explode('/',$type);
$filesize = (int) (strlen(rtrim($imageData, '=')) * 3 / 4);
return $filesize <= $size ? true : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.