如何从php中的base 64字符串获取图像大小

时间:2014-07-09 05:14:47

标签: php file-upload base64

我得到图像字符串的基础64我必须在文件夹中移动并将图像路径存储在数据库中但我必须限制文件大小。我该怎么做:

我从base 64字符串生成图像的代码如下:

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

但是从这里得到文件的宽度和高度。有人告诉我如何从这里得到文件大小。谢谢

5 个答案:

答案 0 :(得分:4)

请检查:

解码后,请尝试使用此getimagesizefromstring(),如果您使用PHP 5.4,如果使用PHP 5.3,则可以使用以下方法进行检查。

<?php
if (!function_exists('getimagesizefromstring')) {
    function getimagesizefromstring($data)
    {
        $uri = 'data://application/octet-stream;base64,' . base64_encode($data);
        return getimagesize($uri);
    }
}

答案 1 :(得分:2)

getimagesize()函数也应该只使用数据URI:

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

答案 2 :(得分:1)

在移动到文件夹之前获取图像大小的想法并不好。然后我决定将图像移动到临时文件夹并使用图像路径获取大小,然后验证图像大小。这样我就可以轻松验证图像大小并防止如果大小限制超过它,它将存储在数据库中。谢谢每个人的时间。

我的更新代码如下:

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

}

答案 3 :(得分:1)

尝试以字节,KB,MB为单位获取文件大小。

sample_images = array(sample_images).reshape(1, 256, 256, 6)

答案 4 :(得分:1)

由于base-64算法将图片大小增加,最多达到 33%,因此我强烈建议您使用这种方式:< / p>

$size = (int)(strlen(rtrim($image, '=')) * 0.75); // in byte