Laravel Validation is compulsory on saving and uploading data to the application and database. We have learnt on how to upload a single and multiple images in Laravel applications. However, we should always be careful of validation rules when saving data. Especially for images and videos, size and dimensions rules are crucial. Let’s learn on how to check image dimension on uploads in Laravel in the best way.
There are two methods for this. The steps are very simple and easy.
Image Dimensions Using Laravel Intervention
The first method is to use the Laravel Intervention package. You can include this package in your project using the composer command as shown below.
composer require intervention/image_dimensions
Secondly, to get the width and height of an image, you can make use of the “Image” façade provided by the package. It loads the image resource through a “make” method. You should add this code in the web.php file as shown below.
<?php
Route::get('image-data', function () {
$imageData = \Storage::get('image_data.jpg');
$width = Image::make($imageData)->width(); // getting the image width
$height = Image::make($imageData)->height(); // getting the image height
return [
'width' => $width,
'height' => $height,
];
});
Once the image is loaded into “Intervention Image” class, you can call the “width()” and “height()” methods. The code logic above is written within a route and returns the width and height of the image.
Image Dimensions using the ‘getimagesize’ method
The second way is to use the “getimagesize()” method, that is present in PHP by default. You can use it simple, by calling the function and passing in the image resource. For example, as shown below.
<?php
Route::get('image-data', function () {
$imageData = \Storage::get('image_data.jpg');
$width = getimagesize($imageData)[0]; // getting the image width
$height = getimagesize($imageData)[1] // getting the image height
return [
'width' => $width,
'height' => $height,
];
});
Here, when you will visit the route “/image-data” you can get the width and height of the “image_data.jpg” file.
Hope you enjoyed the article and find the two simple methods helpful check Image dimension on uploads.