How to Use the PHP getimagesize() Function

09/06/2021

Contents

In this article, you will learn how to use the PHP getimagesize() function.

PHP getimagesize() Function

The getimagesize() function in PHP is used to retrieve information about an image file, such as its width, height, and format.

This function is available in PHP 4 and later versions.

Syntax:
array getimagesize ( string $filename [, array &$imageinfo ] );
Parameters:
  • $filename: The path to the image file. It can be either a local file path or a URL.
  • $imageinfo: An optional parameter that can be passed by reference. If specified, it will be filled with additional information about the image, such as the channels, bits, and the height and width units.
Return value:

The function returns an array of information about the image file. The array contains the following elements:

  • 0: Width of the image in pixels.
  • 1: Height of the image in pixels.
  • 2: Image format as an integer constant. The format can be one of the following: IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_TIFF_II (or TIFF), IMAGETYPE_TIFF_MM (or TIFF), IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO.
  • 3: A string containing the height and width information in the format “height=” . $height . ” width=” . $width.
  • “bits”: The number of bits for each color channel.
  • “channels”: The number of color channels in the image.
  • “mime”: The MIME type of the image, such as “image/jpeg”, “image/png”, “image/gif”, etc.

The getimagesize() function will return false if the file is not a valid image or if the function is unable to read the file.

Example:
<?php
  $image_path = "/path/to/image.jpg";
  $image_info = getimagesize($image_path);

  $width = $image_info[0];
  $height = $image_info[1];
  $format = $image_info['mime'];
?>

The function returns an array of information about the image, where the first two elements (index 0 and 1) are the width and height of the image, respectively. The mime key in the array contains the format of the image.

Note: The function uses the gd library to retrieve the image information, so make sure that the library is installed and enabled on your server.