Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image size from base 64 string in php

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

like image 848
Randhir Avatar asked Jul 09 '14 05:07

Randhir


People also ask

How is Base64 image size calculated?

Base64 encodes 3 bytes of binary data on 4 characters. So to get the size of the original data, you juste have to multiply the stringLength (minus the header) by 3/4.

How decode Base64 in PHP?

The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64. Parameters: This function accepts two parameter as mentioned above and described below: $data: It is mandatory parameter which contains the encoded string. $strict: It is an optional parameter.

Does Base64 change size?

Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.


2 Answers

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

$Image = "MyBase64StringHere";
$size = getimagesize($Image);
like image 151
Ja͢ck Avatar answered Oct 12 '22 00:10

Ja͢ck


Since that the base-64 algorithm increases the image size up to 33%, i strongly recommend you to use this way:

$size = (int)(strlen(rtrim($image, '=')) * 0.75); // in byte
like image 25
Mehran Nasr Avatar answered Oct 12 '22 01:10

Mehran Nasr