验证laravel中的base64解码图像 [英] Validate a base64 decoded image in laravel
问题描述
我试图从PUT请求中获取图片以更新用户图片(使用邮递员),并使其通过Laravel 5.2中的验证,以使邮递员中的调用使用以下网址:
Im trying to get a image from a PUT request for update a user picture(using postman), and make it pass through a validation in Laravel 5.2, for making the call in postman use the following url:
http://localhost:8000/api/v1/users?_method = PUT
并使用这样的json将图片字符串发送到正文中:
and send the image string in the body, using a json like this:
{
"picture" : "data:image/png;base64,this-is-the-base64-encode-string"
}
在控制器中,尝试使用多种方法解码图像并尝试通过验证:
In the controller try a lot of differents ways for decode the image and try to pass the validation:
-
首先,我尝试过:
First I tried this:
$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);
然后我尝试了这个:
Then I tried this:
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/ ),并且不要通过:
Try to use the intervention image library (http://image.intervention.io/) and don't pass:
$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');
}
这是用户模型中的验证:
this is the validation in the User-model:
public static function rulesForUpdate() {
return [
'first_name' => 'max:255',
'last_name' => 'max:255',
'picture' => 'image|max:5000|mimes:jpeg,png'
];
}
推荐答案
您可以扩展Laravel的Validator类.
You can extend the Validator class of Laravel.
但是无论如何尝试
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'
);
这篇关于验证laravel中的base64解码图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!