Laravel 5中的图像验证Intervention

21

我在Laravel 5.1中安装了 intervention ,并且我正在使用图像上传和调整大小的类似以下方式:

Route::post('/upload', function()
{
Image::make(Input::file('photo'))->resize(300, 200)->save('foo.jpg');
});

我不明白的是,Intervention是如何处理上传图片的验证过程的?我的意思是,Intervention是否已经内置了图像验证检查,还是我需要使用Laravel的Validation手动添加以检查文件格式、文件大小等?我已经阅读了Intervention文档,但在使用Intervention和Laravel进行图像验证时,我找不到有关其工作原理的信息。

请问有人可以指点我正确的方向吗?


1
你可能需要查看这个链接 https://laracasts.com/discuss/channels/general-discussion/validating-an-image-laravel-5 和这个链接 http://tutsnare.com/upload-files-in-laravel/,据我所知,intervention 中没有内容验证。 - Maytham Fahmi
谢谢@maytham,你的评论确实帮了我很多,指明了正确的方向。我已经发布了我现在正在使用的解决方案。 :) - Neel
欢迎,这是我的投票。 - Maytham Fahmi
1
顺便说一下,我必须发布一些对Laravel开发人员可能有趣的内容,自动保护图像并添加帮助程序。http://stackoverflow.com/questions/31665553/how-to-automatically-register-helpers-class-in-serviceprovider/31665919#31665919和https://dev59.com/7F0a5IYBdhLWcg3wH1ly#30682456 - Maytham Fahmi
1
@sajad 你卡在哪里了? - Maytham Fahmi
显示剩余4条评论
5个回答

43

感谢@maytham的评论,指导我正确方向。

我发现图像处理 Intervention 并不会进行任何验证。所有的图像验证都必须在上传到 Intervention 之前完成。幸好 Laravel 内置了像 imagemime 类型这样的验证器,使图像验证变得非常简单。现在我先验证文件输入,然后再将其传递给 Image Intervention。

在处理 Intervention 的 Image 类之前进行验证器检查:

 Route::post('/upload', function()
 {
    $postData = $request->only('file');
    $file = $postData['file'];

    // Build the input for validation
    $fileArray = array('image' => $file);

    // Tell the validator that this file should be an image
    $rules = array(
      'image' => 'mimes:jpeg,jpg,png,gif|required|max:10000' // max 10000kb
    );

    // Now pass the input and rules into the validator
    $validator = Validator::make($fileArray, $rules);

    // Check to see if validation fails or passes
    if ($validator->fails())
    {
          // Redirect or return json to frontend with a helpful message to inform the user 
          // that the provided file was not an adequate type
          return response()->json(['error' => $validator->errors()->getMessages()], 400);
    } else
    {
        // Store the File Now
        // read image from temporary file
        Image::make($file)->resize(300, 200)->save('foo.jpg');
    };
 });

希望这能有所帮助。


$file = Input::file('photo'); 中的 'photo' 是从哪里来的? - Chriz74
1
@Chriz74 是表单输入的名称。 - Christian Giupponi
2
为什么不使用 $file = $request->photo;? - Chriz74
非常好的建议 @Chriz74 ,我已经更新了代码,使用$request代替了在表单中使用输入名称时使用 Input:: - Neel
如果我想获取图像的最大尺寸怎么办? - jhon

17

简单地说,集成这个来进行验证

$this->validate($request, [
    'file' => ['image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
]);

4

图片支持的格式 http://image.intervention.io/getting_started/formats

可读取的图像格式取决于您选择的驱动程序(GD或Imagick)以及本地配置。默认情况下,Intervention Image目前支持以下主要格式。

    JPEG PNG GIF TIF BMP ICO PSD WebP

GD ✔️ ✔️ ✔️ - - - - ✔️ *

Imagick ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ *

  • 若要使用imagewebp()函数支持WebP格式,必须在PHP 5 >= 5.5.0 或者 PHP 7中使用GD驱动。如果使用的是Imagick,则必须编译libwebp以支持WebP格式。

请查看make方法的文档以了解如何从不同的来源读取图像格式,以及编码和保存图像的方法。

注意: (Intervention Image是一款开源的PHP图像处理和操作库 http://image.intervention.io/). 此库不验证任何验证规则,这由Larval的Validator类完成。

Laravel Doc https://laravel.com/docs/5.7/validation

Tips 1: (请求验证)

$request->validate([
   'title' => 'required|unique:posts|max:255',
   'body' => 'required',
   'publish_at' => 'nullable|date',
]); 

// Retrieve the validated input data...
$validated = $request->validated(); //laravel 5.7

提示2:(控制器验证)

$validator = Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

if ($validator->fails()) {
    return redirect('post/create')
        ->withErrors($validator)
        ->withInput();
}

2
我有一个自定义表单,但是这个变量不起作用。因此,我使用了正则表达式验证。
像这样:
  client_photo' => 'required|regex:/^data:image/'

也许这对某些人会有帮助。

0
public function store(Request $request)
{
    $room = 1;

    if ($room == 1) {
        //image upload start
        if ($request->hasfile('photos')) {
            foreach ($request->file('photos') as $image) {
                // dd($request->file('photos'));
                $rand = mt_rand(100000, 999999);
                $name = time() . "_"  . $rand . "." . $image->getClientOriginalExtension();
                $name_thumb = time() . "_"  . $rand . "_thumb." . $image->getClientOriginalExtension();
                //return response()->json(['a'=>storage_path() . '/app/public/postimages/'. $name]);
                //move image to postimages folder
                //dd('ok');
                //  public_path().'/images/
                $image->move(public_path() . '/postimages/', $name);
                // 1280
                $resizedImage = Image::make(public_path() . '/postimages/' . $name)->resize(300, null, function ($constraint) {
                    $constraint->aspectRatio();
                });

                // save file as jpg with medium quality
                $resizedImage->save(public_path() . '/postimages/' . $name, 60);
                // $resizedImage_thumb->save(public_path() . '/postimages/' . $name_thumb, 60);
                $data[] = $name;
                       
                //insert into picture table
                $pic = new Photo();
                $pic->name = $name;
                $room->photos()->save($pic);
            }
        }

        return response()->json([
            'success' => true, 
            'message' => 'Room Created!!'
        ], 200);
    } else {
        return response()->json([
            'success' => false, 
            'message' => 'Error!!'
        ]);
    }
}

  1. 必须使用命令 composer require intervention/image。
  2. 必须使用 Intervention\Image\ImageManagerStatic 作为 Image。
- Mohammad Ali Abdullah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接