Yii2 将图像 post 验证为数据 url

Yii2 validate image post as data url

我需要验证作为数据 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.

问题: 图像验证不适用于图像为字符串的 post 数据(数据 url)。

请帮忙验证图片。

更新: Other question 提到重复与 Yii2 框架无关。我正在寻找遵循 Yii2 的 MVC 流程的答案。

我正在回答我自己的问题,因为我对类似问题中找到的任何其他答案都不完全满意,以便未来的读者受益。

解决方法是使用custom validator.

我按照上述指南创建了一个:

在我的个人资料模型中,我将规则更改为:

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() 从字符串中检索图像信息。