How To Get Image Width And Height With PHP?

19 June 2023 601 Reading time: 57 second

To get the width and height of an image using PHP, you can make use of the getimagesize() function. Here's an example:

<?php

$imagePath = 'path_to_your_image.jpg'; // Replace with the actual path to your image file

// Get the image size information
$imageSize = getimagesize($imagePath);

if ($imageSize !== false) {
    $width = $imageSize[0];  // Image width
    $height = $imageSize[1]; // Image height

    echo "Width: $width pixels<br>";
    echo "Height: $height pixels";
} else {
    echo "Failed to get image size.";
}
?>

In this code snippet, replace 'path_to_your_image.jpg' with the actual path to your image file. The getimagesize() function returns an array containing the width and height of the image in pixels, along with other information such as the image type and MIME type. The width is accessed using index 0, and the height is accessed using index 1 in the returned array.

Make sure you have the GD library enabled in your PHP configuration, as getimagesize() relies on it to function correctly.

Similar articles