的答案
我需要验证上载的图像为数据URL,该图像是:
{profile: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAA...McAAAAASUVORK5CYII="}
我的个人资料模型具有以下规则:
return [
...
['profile', 'image', 'extensions' => 'png, jpg',
'minWidth' => 50, 'maxWidth' => 150,
'minHeight' => 50, 'maxHeight' => 150,
],
...
];
我的控制器正在保存配置文件而没有验证:
$my=new Profile();
$my->profile=Yii::$app->request->post("profile");
$result=$my->save(); //Always true even when dimensions are out of bound.
问题:图像验证不适用于使用图像为字符串(数据URL)的帖子数据。
请帮助验证图像。
更新:提到重复的其他问题与YII2框架无关。我正在寻找将遵循yii2的MVC流。
我正在回答自己的问题,因为我对在类似问题中发现的任何其他答案都不满意,以便未来的读者可以得到良好的问题。
解决方案是使用自定义验证器。
我创建了一个以下指南:
在我的个人资料模型中,我更改了规则为:
return [
...
['profile', 'imageString', 'params' => ['mimes'=>['image/png', 'image/jpeg'],
'minWidth' => 50, 'maxWidth' => 150,
'minHeight' => 50, 'maxHeight' => 150,]
]
...
];
并添加了一个函数:
public function imageString($attr, $params){
$img=explode(";",$this->$attr,2); //explodes into two part each containing image type and data
if(count($img)<2){
//expects two parts, else adds error.
$this->addError($attr, 'Invalid imageString format.');
return;
}
if(stripos($img[0],"data:")!==0 && stripos($img[1],"base64,")!==0){
//expects "data:" and "base64," as starting strings for each parts (not case sensitive).
$this->addError($attr, 'Invalid imageString format.');
return;
}
$reps=[0,0];
//removes the occurance of above starting strings (not case sensitive).
$img[0]=str_ireplace("data:","",$img[0],$reps[0]);
$img[1]=str_ireplace("base64,","",$img[1],$reps[1]);
if(array_sum($reps)>2){
//expects total occurances to be exact 2.
$this->addError($attr, 'Invalid imageString format.');
return;
}
$img[1]=getimagesizefromstring(base64_decode($img[1]));
if(!$img[1]){
//expects data to be valid image.
$this->addError($attr, 'Invalid imageString format.');
return;
}
foreach($params as $key => $val){
switch($key){
case "mimes": //check mime type of image.
$val = array_map('strtolower', $val);
if(!in_array(strtolower($img[0]),$val) || !in_array($img[1]['mime'],$val)){
$this->addError($attr, 'Invalid imageString mime type.');
}
break;
case "minWidth": //check minimum width of image.
if($img[1][0]<$val){
$this->addError($attr, "Image width is lower than $val.");
}
break;
case "maxWidth": //check maximum width of image.
if($img[1][0]>$val){
$this->addError($attr, "Image width is greater than $val.");
}
break;
case "minHeight": //check minimum height of image.
if($img[1][1]<$val){
$this->addError($attr, "Image height is lower than $val.");
}
break;
case "maxHeight": //check maximum height of image.
if($img[1][1]>$val){
$this->addError($attr, "Image height is greater than $val.");
}
break;
}
}
}
此功能使用getimagesizefromstring()从字符串中检索图像信息。