Skip to content

Instantly share code, notes, and snippets.

@fdorantesm fdorantesm/helpers,js
Last active Oct 2, 2018

Embed
What would you like to do?
Base64 File helpers
function toBytes(value){
var unit = value.substr(-2)
var size = value.replace(unit, '')
var result
switch(unit){
case 'kb': result = size * 1000; break;
case 'mb': result = size * 1000000; break;
case 'gb': result = size * 1000000000; break;
case 'tb': result = size * 1000000000000; break;
case 'pb': result = size * 1000000000000000; break;
default: result = size;
}
return result;
}
function smallerThan(data, size){
$uri = data.substring(5)
var [$type, $imageData] = data.split(';base64,')
var [,$extension] = $type.split('/')
// $filesize = strlen(rtrim($imageData, '=')) * 3 / 4);
$filesize = ($imageData.replace(/~+$/,'').length * 3 /4)
return $filesize <= size ? true : false;
}
<?php
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);
// in_array($extension, ["png","jpeg","gif"]){
// $funct = "imagecreafrom".$extension;
// if ($func($imageData)) {
// # code...
// }
// }
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.