Custom Laravel Validator for image dimensions
Extra validation rules for dealing with images in Laravel 5.
NOTE: Version 2.x of this package is designed to work with Laravel 5. If you are using Laravel 4, then checkout the
1.xbranch and use the latest version there.
Install the package through Composer.
composer require "cviebrock/image-validator:^2.1"
Add the following to your
providers array in
'providers' => [ ... \Cviebrock\ImageValidator\ImageValidatorServiceProvider::class, ],
Use it like any
Validator rule. The package offers two rules for image validation:
$rules = [ 'my_image_field' => 'image_size:<width>[,<height>]', ];
The values for width and _height can be integers, or integers with a modifier prefix:
=300means the dimension must be exactly 300 pixels.
<300means the dimension must be less than 300 pixels
<=300means the dimension must be less than or equal to 300 pixels
>300means the dimension must be greater than 300 pixels
>=300means the dimension must be greater than or equal to 300 pixels
200-300means the dimension must be betweem 200 and 300 pixels (inclusive)
*means the dimension can be any value
If you only pass one value, it's assumed to apply to both dimensions (i.e. a square image with the given dimensions).
$rules = [ 'my_image_field' => 'image_aspect:<ratio>', ];
The value for ratio represents width ÷ height and be either a decimal or two values (width, height; both integers):
The value (or first value, if providing height and width) can also be prefixed with a tilde
in which case the orientation does not matter:
~3,4means the image can have an aspect ratio of either 3:4 or 4:3.
Note that you may run into issues with floating point rounding.
// logo must be 300px wide by 400px tall $rules = [ 'logo' => 'required|image|image_size:300,400', ]; // logo must be less than or equal to 300x300px. $rules = [ 'logo' => 'required|image|image_size:<=300', ]; // logo must be 300px wide but can be any height $rules = [ 'logo' => 'required|image|image_size:300,*', ]; // logo must be at least 100px tall and 200-300 pixels wide (inclusive) $rules = [ 'logo' => 'required|image|image_size:>=100,200-300', ]; // logo must be square $rules = [ 'logo' => 'required|image|image_aspect:1', ]; // logo must be ready for the big screen TV :) $rules = [ 'logo' => 'required|image|image_aspect:16,9', ];
Thanks to everyone who has contributed to this project!
Please use Github for reporting bugs, and making comments or suggestions.
See CONTRIBUTING.md for how to contribute changes.
Copyright 2013 Colin Viebrock
Lots of thanks to https://bitbucket.org/hampel/validate-laravel for the structure of creating a package to add validator rules to Laravel, and setting up useful unit tests.