my ($width, $height, $format) = ImageSize($filePath);


This Perl function returns the width, height, and format of an image file. It supports GIF, JPG, BMP, and PNG formats. It determines the image type by reading the first few characters of the file.

FormatLengthImage file header
GIF6"GIF87a" or "GIF89a"
PNG80x89504E470D0A1A0A that is "\x89PNG\r\n\x1A\n"

If you really want to look deep inside image files, I recommend Encylopedia of Graphics File Formats. The book is out of print, but you should be able to find a used copy. There is also an online copy hosted by If you find something to replace it, let me know.


If an error occurs, the return values are negative. The first number indicates an open error or which image type failed:
-1open of image file failed
-2GIF failure
-3JPG failure
-4BMP failure
-5PNG failure

The second number indicates the specific error that occurred. For image failures, it is the point in the image file that an error occurred. Consult the source for the meaning of these failures.


Click any image to open the actual file passed to ImageSize in your browser.

exelana.gifjackass.jpg uparrow.bmpgods.pngfizban.txt
85,103,"gif" 31,31,"jpg" 16,16,"bmp" 125,125,"png" 100,100,"gif"

Send me reports of any errors or suggestions you have about my Perl scripts.

The code described on this page is Copyright 2003, 2007 Tony Lewis <>.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see <>.