Posts Learn Components Snippets Categories Tags About
/

How to get image width and height in Laravel

Learn how to get an uploaded image width and height in Laravel the easy way. Get to know how to use Laravel Intervention to get image width and height or using the native PHP function.

Created on Sep 05, 2021

19 views

In this short snippet, you will learn the ways to get the image width and height in the Laravel application. The steps are very simple so let's get started.

Method 1: Getting Width and Height Using Laravel Intervention


The first method is to use Laravel Intervention package and you can include this package in your project using the composer command below.
composer require intervention/image
Now to get the image width and height you can make use of the "Image" facade provided by the package and load the image resource through the "make" method. Once the image is loaded into "Intervention Image" class, you will be able to call the "width()" and "height()" methods. For this example, we will write the code logic from within a route and return the image width and height.
<?php // routes/web.php

Route::get('image-data', function () {
    $imageData = \Storage::get('some-image-in-the-storage.jpg');

    $width = Image::make($imageData)->width(); // getting the image width
    $height = Image::make($imageData)->height(); // getting the image height

    return [
        'width' => $width,
        'height' => $height,
    ];
});

Method 2: Getting Width and Height Using "getimagesize" Method


The second method is to use the "getimagesize()" function available by default from PHP. To use this function you can just call the function and pass in the image resource.
<?php

getimagesize($yourImageHere)
The full code example will be as follows.
<?php // routes/web.php

Route::get('image-data', function () {
    $imageData = \Storage::get('some-image-in-the-storage.jpg');

    $width = getimagesize($imageData)[0]; // getting the image width
    $height = getimagesize($imageData)[1] // getting the image height

    return [
        'width' => $width,
        'height' => $height,
    ];
});
Now when you visit the route "/image-data" you will get the width and height of the "some-image-in-the-storage.jpg" data.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to get image width and height in Laravel