gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:52:36 26 4
gpt4 key购买 nike

我正在尝试从 PUT 请求中获取图像以更新用户图片(使用 postman ),并使其通过 Laravel 5.2 中的验证,以便在 postman 中使用以下 url 进行调用:

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

并在正文中发送图像字符串,使用像这样的 json:

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

在 Controller 中尝试多种不同的方式来解码图像并尝试通过验证:

  1. 首先我尝试了这个:

    $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);
  2. 然后我尝试了这个:

    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');
  3. 尝试使用干预图像库(http://image.intervention.io/),不要通过:

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

这是 Controller 中的验证:

    $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'
];
}

最佳答案

如果您无论如何都在使用干预,那么您可以将其用于自定义验证规则。我有一个叫做“imageable”的。它基本上确保给定的输入能够转换为干预图像。 Base64 数据图像字符串将通过。一串“foo”不会。

Validator::extend('imageable', function ($attribute, $value, $params, $validator) {
try {
ImageManagerStatic::make($value);
return true;
} catch (\Exception $e) {
return false;
}
});

这显然只是检查输入是否能够转换为图像。但是,它应该以用例的形式向您展示如何利用干预及其任何方法来创建自定义规则。

关于php - 在 laravel 中验证 base64 解码图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39042731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com