Image Validation in Laravel 5 Intervention
Asked Answered
M

5

21

I have installed intervention in Laravel 5.1 and I am using the image upload and resize something like this:

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

What I dont understand is, how does intervention process the validation for the uploaded image? I mean, does intervention already has the inbuild image validation check in it or is that something I need to manually add using Laravel Validation to check for the file formats, file sizes, etc..? I have read through the intervention docs and I couldnt find info on how image validation works when using intervention with laravel.

Can someone point me in the right direction please..

Mcclean answered 8/8, 2015 at 13:6 Comment(9)
You might take look at this laracasts.com/discuss/channels/general-discussion/… and this tutsnare.com/upload-files-in-laravel as far as I know there is no content validation in intervention.Undertone
Thank you @maytham Your comment certainly helped me a lot in pointing in the right direction. I have posted my solution I am using now. :)Mcclean
You are welcome, here is my vote also.Undertone
You are very kind :)Mcclean
btw I have to post that might be interesting for you as Laravel developer, protecting images and adding helpers automatically. #31666053 and #30682921Undertone
That certainly does help. Thank you for sharing.Mcclean
@maytham-ɯɐɥıλɐɯ: can you help me?Prosaism
@sajad where are stuckUndertone
@maytham-ɯɐɥıλɐɯ: here #33720059. this is my last question and will not annoy you more ...Prosaism
M
43

Thanks to @maytham for his comments which pointed me in the right direction.

What I found out is that the Image Intervention does not do any Validation by itself. All Image Validation has to be done before before its passed over to Image intervention for uploading. Thanks to Laravel's inbuilt Validators like image and mime types which makes the image validation really easy. This is what I have now where I am validating the file input first before passing it over to Image Intervention.

Validator Check Before Processing Intervention Image Class:

 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');
    };
 });

Hope this helps.

Mcclean answered 9/8, 2015 at 13:31 Comment(5)
where does that 'photo' come from in $file = Input::file('photo'); ?Trypanosome
@Trypanosome that is the input name in the formShockey
why not use $file = $request->photo; ?Trypanosome
Good point @Trypanosome Have updated code with $request instead of using Input:: using input name in form.Mcclean
what if I want to get max size of the image?Levine
T
19

Simply, Integrate this to to get validation

$this->validate($request, [
    'file' => ['image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
]);
Traject answered 28/12, 2017 at 4:35 Comment(0)
A
4

Image Supported Formats http://image.intervention.io/getting_started/formats

The readable image formats depend on the chosen driver (GD or Imagick) and your local configuration. By default Intervention Image currently supports the following major formats.

    JPEG PNG GIF TIF BMP ICO PSD WebP

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

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

  • For WebP support GD driver must be used with PHP 5 >= 5.5.0 or PHP 7 in order to use imagewebp(). If Imagick is used, it must be compiled with libwebp for WebP support.

See documentation of make method to see how to read image formats from different sources, respectively encode and save to learn how to output images.

NOTE: (Intervention Image is an open source PHP image handling and manipulation library http://image.intervention.io/). This library does not validate any validation Rules, It was done by Larval Validator class

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

Tips 1: (Request validation)

$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

Tips 2: (controller validation)

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

if ($validator->fails()) {
    return redirect('post/create')
        ->withErrors($validator)
        ->withInput();
}
Adrienneadrift answered 12/2, 2019 at 7:0 Comment(0)
S
2

i have custum form, and this variant does not work. So i used regexp validation

like this:

  client_photo' => 'required|regex:/^data:image/'

may be it will be helpful for someone

Summerly answered 6/1, 2017 at 7:20 Comment(0)
D
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!!'
        ]);
    }
}
Dichromatism answered 16/4, 2021 at 16:13 Comment(1)
** must be use 1. use command composer require intervention/image. 2. use Intervention\Image\ImageManagerStatic as Image;Dichromatism

© 2022 - 2024 — McMap. All rights reserved.