Validate a base64 decoded image in laravel
我正在尝试从PUT请求中获取图片以更新用户图片(使用邮递员),并使其通过Laravel 5.2中的验证,以使邮递员中的呼叫使用以下网址:
http:// localhost:8000 / api / v1 / users?_method = PUT
并使用这样的json将图片字符串发送到正文中:
1 2 3 | { "picture" :"data:image/png;base64,this-is-the-base64-encode-string" } |
在控制器中,尝试使用多种方法解码图像并尝试通过验证:
首先,我尝试了此操作:
1 2 3 4 5 6 | $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); |
然后我尝试了此操作:
1 2 3 4 5 6 7 8 | 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/),但不要通过:
1 2 3 | $image = Image::make($data); $image->save(app_path() . 'test2.png'); $image = Image::make(app_path() . 'test1.png'); |
这是控制器中的验证:
1 2 3 4 5 6 7 8 9 10 | $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'); } |
这是用户模型中的验证:
1 2 3 4 5 6 7 | public static function rulesForUpdate() { return [ 'first_name' => 'max:255', 'last_name' => 'max:255', 'picture' => 'image|max:5000|mimes:jpeg,png' ]; } |
如果仍然使用干预,则可以将其用于自定义验证规则。我有一个叫做"可成像的"。基本上可以确保给定的输入将能够转换为干预图像。 Base64数据图像字符串将通过。字符串" foo"不会。
1 2 3 4 5 6 7 8 | Validator::extend('imageable', function ($attribute, $value, $params, $validator) { try { ImageManagerStatic::make($value); return true; } catch (\\Exception $e) { return false; } }); |
这显然只是检查输入是否能够转换为图像。但是,它应该作为一个用例向您展示如何利用干预及其任何方法来创建自定义规则。
您可以扩展Laravel的Validator类。
Laravel文档
但是无论如何尝试一下
1 2 3 4 5 6 | 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'; }); |
别忘了规则:
1 2 3 |
内部扩展功能中添加此
1 2 3 4 |