Posts Learn Components Snippets Categories Tags Tools About
/

How to Easily Get Image Width and Height in PHP

Learn how to get the image width and height in PHP the easy way. Make use of the built in getimagesize to get the image width, height, mime and etc

Created on Oct 01, 2021

443 views

In this short snippet, you will learn how to easily get image width, height, and metadata in PHP. This can be achieved using the "getimagesize()" PHP built-in method.

getimagesize() method


This method accepts the image path and then will return an array of information. You can extract the value directly using the "list()" method and it's as follows.
<?php

list($width, $height, $type, $attr) = getimagesize("some-image.jpg");
The output of the above code will be like below.
[
    0 => 200,
    1 => 120,
    2 => 18,
    3 => 'width="200" height="120"',
    'bits' => 8,
    'mime' => 'image/webp',
]

getimagesize with Laravel Storage


Do note that you can also pass in the image path from the Laravel model like below. Imagine you have a Post model that store the path of the image that's located within the storage directory.
<?php

$path = storage_path('app/public/' . Post::first()->poster);

list($width, $height, $type, $attr) = getimagesize($path);

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)