Skip to content

Instantly share code, notes, and snippets.

@fdorantesm
Created August 26, 2019 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdorantesm/2a03ea368050138aa0411946d725783f to your computer and use it in GitHub Desktop.
Save fdorantesm/2a03ea368050138aa0411946d725783f to your computer and use it in GitHub Desktop.
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