我使用的是JavaScript客户端图片上传器和编辑器,通过URI图片发布到服务器。
示例代码:
$_POST['image_data']="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAO4AAAA6CAYAAAC........"
生成的图像很小(20kb-30kb),我将它直接保存到数据库而不是文件中(因为我之后也将它直接嵌入到CSS中)。
在将数据添加到数据库之前,如何验证发布的数据,使其尺寸和尺寸不会太大?我还需要检查数据URI,以使图像有精确的尺寸(例如:100x100),否则会向用户显示错误。
为了澄清,我将图像放在一个post变量中,而不是将它保存到文件中。
答案 0 :(得分:1)
第二种解决方案,如果你不能写任何东西到磁盘上
$_POST["image_data"] = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
function check_uri_image($data, $width=100, $height=100, $mime="image/png"){
$success = false;
if(preg_match("#^data:(image/(gif|png|jpeg));base64,(.*)$#mi", $data, $matches)){
if($img = imagecreatefromstring(base64_decode($matches[3]))){
if((imagesx($img) == $width) && (imagesy($img) == $height)){
if(strtolower($matches[1]) == $mime){
$success = true;
}
}
imagedestroy($img);
}
}
return $success;
}
var_dump(check_uri_image($_POST["image_data"], 16, 16, "image/gif"));
答案 1 :(得分:0)
请尝试:
$_POST["image_data"] = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
function check_uri_image($data, $width=100, $height=100, $mime="image/png"){
$success = false;
if(preg_match("#^data:image/(gif|png|jpeg);base64,(.*)$#mi", $data, $matches)){
if($tmp = tempnam(sys_get_temp_dir(), "datauri.")){
if($fh = fopen($tmp, "wb")){
fwrite($fh, base64_decode($matches[2]));
fclose($fh);
$info = getimagesize($tmp);
if(is_array($info)){
if(($info[0] == $width) && ($info[1] == $height) && ($info["mime"] == $mime)){
$success = true;
}
}
unlink($tmp);
}
}
}
return $success;
}
var_dump(check_uri_image($_POST["image_data"], 16, 16, "image/gif"));
?>