客户端直接提交过来的图片base64字符串,需要在php中进行大小限制,那我们在PHP中怎么得到原图片的大小并对其进行大小验证呢?
下面这个方法将会帮你解决这个问题。
/**
* base64大小验证
* @param string $base64
* @param int $maxSize
* @return bool
*/
public function base64sizeValidation(string $base64, int $maxSize)
{
$base64 = str_replace('data:image/jpeg;base64,', '', $base64);
$base64 = str_replace('=', '', $base64);
$imgLen = strlen($base64);
$fileSize = $imgLen - ($imgLen / 8) * 2;
$fileSize = number_format(($fileSize / 1024), 2);
if ($fileSize > $maxSize) {
return false;
}
return true;
}