How to get image size from base 64 string in php
Please check this :
After decoding, try with this : getimagesizefromstring()
, if you are with PHP 5.4
, if using PHP 5.3
, then you can check with the following method.
<?php
if (!function_exists('getimagesizefromstring')) {
function getimagesizefromstring($data)
{
$uri = 'data://application/octet-stream;base64,' . base64_encode($data);
return getimagesize($uri);
}
}
The getimagesize()
function should just work with Data URI as well:
$Image = "MyBase64StringHere";
$size = getimagesize($Image);
The idea to get image size before moving to folder is not good.Then I decided to move image to a temporary folder and get the size using image path and then validate image size.With this I can easily validate image size and prevent it to store in database if size limit exceeds.Thanks every one for their time.
My updated code is like:
/** if image is attached with request **/
$Image = "Yourbase64StringHere";
list($type, $Image) = explode(';', $Image);
list(, $Image) = explode(',', $Image);
/** decode the base 64 image **/
$Image = base64_decode($Image);
/* move image to temp folder */
$TempPath = 'temp/'.time().".jpg";
file_put_contents($TempPath, $Image);
$ImageSize = filesize($TempPath);/* get the image size */
if($ImageSize < 83889000){ /* limit size to 10 mb */
/** move the uploaded image **/
$path = 'uploads/'.time().".jpg";
file_put_contents($path, $Image);
$Image = $path;
/** get the image path and store in database **/
unlink($TempPath);/* delete the temporay file */
}else{
unlink($TempPath);/* delete the temporay file */
/** image size limit exceded **/
}