加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 在laravel中验证base64解码图像

发布时间:2020-12-14 19:36:28 所属栏目:大数据 来源:网络整理
导读:我试图从PUT请求获取图像以更新用户图片(使用邮递员),并使其通过Laravel 5.2中的验证,以便在邮递员中使用以下URL进行调用: http://localhost:8000/api/v1/users?_method=PUT 并使用像这样的json在体内发送图像字符串: { "picture" : "data:image/png;base6
我试图从PUT请求获取图像以更新用户图片(使用邮递员),并使其通过Laravel 5.2中的验证,以便在邮递员中使用以下URL进行调用:

http://localhost:8000/api/v1/users?_method=PUT

并使用像这样的json在体内发送图像字符串:

{
    "picture" : "data:image/png;base64,this-is-the-base64-encode-string"
}

在控制器中尝试许多不同的方法来解码图像并尝试通过验证:

>首先我试过这个:

$data = request->input('picture');
$data = str_replace('data:image/png;base64,','',$data);
$data = str_replace(' ','+',$data);
$image = base64_decode($data);
$file = app_path() . uniqid() . '.png';
$success = file_put_contents($file,$image);

>然后我尝试了这个:

list($type,$data) = explode(';',$data);
list(,$data) = explode(',$data);
$data = base64_decode($data);
$typeFile = explode(':',$type);
$extension = explode('/',$typeFile[1]);
$ext = $extension[1];
Storage::put(public_path() . '/prueba.' . $ext,$data);
$contents = Storage::get(base_path() . '/public/prueba.png');

>尝试使用干预图像库(http://image.intervention.io/)并且不通过:

$image = Image::make($data);
$image->save(app_path() . 'test2.png');
$image = Image::make(app_path() . 'test1.png');

这是控制器中的验证:

$data = [
        'picture' => $image,'first_name' => $request->input('first_name'),'last_name' => $request->input('last_name')
    ];

    $validator = Validator::make($data,User::rulesForUpdate());
    if ($validator->fails()) {
        return $this->respondFailedParametersValidation('Parameters failed validation for a user picture');
    }

这是用户模型中的验证:

public static function rulesForUpdate() {
    return [
        'first_name' => 'max:255','last_name' => 'max:255','picture' => 'image|max:5000|mimes:jpeg,png'
    ];
}

解决方法

您可以扩展Laravel的Validator类.

Laravel Doc

但无论如何试试这个

Validator::extend('is_png',function($attribute,$value,$params,$validator) {
    $image = base64_decode($value);
    $f = finfo_open();
    $result = finfo_buffer($f,$image,FILEINFO_MIME_TYPE);
    return $result == 'image/png';
});

不要忘记规则:

$rules = array(
   'image' => 'is_png'
);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读