Get an image size with PHP
Posted July 9th, 2008 in PHP
PHP has a function called getimagesize() for getting the width and height from an image. I'm always forgetting the name of the getimagesize() function so I decided to write a post about it and showing some examples and that way maybe I'll remember in the future...
getimagesize() is one of those classic PHP functions which illustrates how bad the naming convention for PHP functions is. Usually words if function names in PHP are separate by and underscore (e.g. it would be get_image_size()) but this is one of those functions that doesn't. Anyway, I digress...
Pass getimagesize() a filename and it will return an array containing the image's width, height, what type of image it is, a text value with the width and height which can be placed directly into an <img> tag and some other stuff detailed below.
For example, if we had a JPEG image called "my-great-photo.jpg" and it was 300 pixels width and 200 pixels high, you could get the image information from it like so:
$info = getimageinfo("my-great-photo.jpg");
Doing print_r($info) would return this, for the above example:
Array
(
[0] => 300
[1] => 200
[2] => 2
[3] => width="300" height="200"
[bits] => 8
[channels] => 3
[mime] => image/jpeg
)
The value in index 0 is the width.
The value in index 1 is the height.
The value in index 2 is one of the IMAGETYPE_XXX constants, such as IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG and IMAGETYPE_BMP.
The value in index 3 is the text string that can be add into an <img> tag.
The 'bits' value indicates the number of bits for each color.
The 'channels' value is either 3 for RGB or 4 for CMYK.
The 'mime' value is the image's mime type and can be used in an HTTP Content-type header.
If the file cannot be opened or parsed, the getimagesize() function will return false. If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.
Related posts:
- PHP fatal libpng error: zlib error (Tuesday, November 4th 2008)
- Image headers with PHP (Tuesday, July 22nd 2008)
- PHP error Call to undefined function ImageCreateFromPNG (Wednesday, January 9th 2008)
Recent posts:
- List installed packages with YUM (Tuesday, December 2nd 2008)
- Monthly Roundup - November 2008 (Monday, December 1st 2008)
- Weekly Roundup - December 1st 2008 (Monday, December 1st 2008)
- Installing subversion on CentOS (Sunday, November 30th 2008)
- GoDaddy 99 cent .com domain coupon code (Saturday, November 29th 2008)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
