Home » Php » file upload – How to get image size from base 64 string in php

file upload – How to get image size from base 64 string in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am getting the base 64 for string for image I have to move in folder and store the image path in database but I have to limit the file size.How can I do this:

My code for generate image from base 64 string is like:

/** if image is attached with request **/
 $Image = "MyBase64StringHere";
 list($type, $Image) = explode(';', $Image);
 list(, $Image)      = explode(',', $Image);

/** decode the base 64 image **/
 $Image = base64_decode($Image);

I have tried to get image size like:
$size =  getimagesize($Image);

But from this am getting file width and height.Can someone tell me how can I get file size from this.Thanks

How to&Answers:

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);
    }
}

Answer:

The getimagesize() function should just work with Data URI as well:

$Image = "MyBase64StringHere";
$size = getimagesize($Image);

Answer:

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 **/

}

Answer:

Try this one get file size in Bytes, KB, MB..

public function getBase64ImageSize($base64Image){ //return memory size in B, KB, MB
    try{
        $size_in_bytes = (int) (strlen(rtrim($base64Image, '=')) * 3 / 4);
        $size_in_kb    = $size_in_bytes / 1024;
        $size_in_mb    = $size_in_kb / 1024;

        return $size_in_mb;
    }
    catch(Exception $e){
        return $e;
    }
}