User Contributed Notes 60 notes

As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

Note that, if you're going to be a good programmer and use named constatnts (IMAGETYPE_JPEG) rather than their values (2), you want to use the IMAGETYPE variants - IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, etc. For some reason, somebody made a horrible decision, and IMG_PNG is actually 4 in my version of PHP, while IMAGETYPE_PNG is 3. It took me a while to figure out why comparing the type against IMG_PNG was failing...

Because most image types allow sections for comments or other irrelevant data. Those section can be used to infiltrate php code onto the server. If these files are stored as sent by the client, files with a ".php" extension can be executed and do tremendous harm.

Though keep in mind that this consumes lots of CPU. So if you're doing something like creating a page of thumbnails this is considerably slower.

So what you can do is use getimagesize() and check if- the width and height are empty strings ("")- and those two values aren't too high

Both indicate that getimagesize() didn't work properly. The latter may happen if getimagesize() thought that it recognized the format and therefore the size properly. I mean if you're looking at pictures that you know are max. 1024x768 and getimagesize() returns a width of e.g. 20234 then it's obvious that something went wrong. In that case use the code mentioned above. Of course if getimagesize() returned small values that are wrong you still get the wrong size. So check your pictures and priorities first.

Note that animated gifs may have frames width different dimensions. This function will not get the first frame's width/height. GIFs define "Logical Screen Descriptor" dimensions, which are the maximum for all frames.

This function returns the width and height of a JPEG image from a string, allowing the dimensions of images stored in a database to be retrieved without writing them to the disk first, or using "imagecreatefromstring" which is very slow in comparison.

It is possible for malformed GIF images to contain PHP and still have valid dimensions.

Programmers need to ensure such images are validated by other tools, or never treated as PHP or other executable types (enforcing appropriate extensions, avoiding user controlled renaming, restricting uploaded images to areas of the website where PHP is not enabled).

On a Debian machine I had a lot of Notices in my log because the system did not understand spaces. While the str_replace and rawurlencode options are ok for remote images, for the local system it is of no use.

I used the following:

getimagesize('"'.$location.'"');

so basically I quoted the location (single_quot-dubble_quote-single_quote).

Well, I am making a script which will resize the image when uploaded, however, i am making a multi-uploader, so i came across with a problem: an efficient way of getting a pictures height and width and storing them in an array to resize later. This is what i came up with:

Rather than making a lengthy function that essentially runs twice (once as width, once as height) I came up with a helpful function that uses variable variables to set a maximum height/width. Hope someone finds this helpful.

// here using Image Magick command line utility to resize image, OR you can use some other package.//@exec("/usr/local/bin/convert $sourceImageFilePath - -resize $newWidthx$newHeight\! $destinationImageFilePath");

It's always good to check out an image's dimensions while attempting to upload to your server or database...especially if it's going to be displayed on a page that doesn't accomodate images beyond a particular size.

I was coming here to see if there was a simple way to get the height, width, and mime type of an image I have uploaded and while I thought the following code would work because it is printed above<?phplist($width, $height, $type, $attr) = getimagesize("img/flag.jpg");?>

it didnt when I tried to echo out $type; so heres my fix, there may be a better way but it works for me!

This is a useful function to display a thumbnail of a whatever image.This piece of code has been lightly modified from an example found on <b>NYPHP.ORG</B>.This function can build a thumbnail of any size you want and display it on your browser!Hope it can be useful for you guys!

I needed a quick way to make a group of images uniformly sized, but only on one page. So creating a new set of thumbnails was overdoing the whole thing. I made up this script that seems to do the trick.

This is just to add to the comment by robertks at hotmail dot com on 05-Mar-2003 12:12 regarding trying to derive the dimensions of a video file. The package referenced (http://www.getid3.org/) had been updated, and below is a script I use to get the size. You can get many other attributes of media files as well.

<?php// include getID3() library (can be in a different directory if full path is specified)include_once('getid3.php');

// Initialize getID3 engine$getID3 = new getID3;

// File to get info from$file_location = './your/path/to/file.mov';

// Get information from the file$fileinfo = $getID3->analyze($file_location);getid3_lib::CopyTagsToComments($fileinfo);

simm posted something interesting about imagick, but usually calling an external binary is not the best way.

You can use the Imagick PHP module . With it, you do not even need to get the image size to generate thubnails...

Here's the code I used :<?php $imh=imagick_readimage($image);imagick_scale($imh,GALLERY_THUMBNAILWIDTH,GALLERY_THUMBNAILHEIGHT);imagick_writeimage($imh,$image_thumb);?>

(I noticed that some hosting companies are now providing the imagick module by default. Using it allows you to accept any type of image from your visitors. Maybe it will be documented on the official PHP website one day or another? )

The Problem:I've just noticed that after upgrading to the PHP 4.3.4 version, the old GetImageSize() should get your attention on pages coded before this new version.

The solutions:So, if you used GetImageSize(), you should now be using getimagesize() - attention to all lower caracters.

Also, you shou certify that the image realy exists, otherwhise you'll get the following error: getimagesize(): Read error!This means that there is no image to "fill" the string and thus you're calling, for example: "images/news/" instead of calling "images/news/03102004a.jpg"

One should now verify if there is an image to be called (example):if($photo1!=""){$size1=getimagesize("images/news/".$photo_news_1"]);$width1=$size1[0];$height1=$size[1];}Here, if $photo_news_1 is set and exists it will be displayed, otherwhise it will be skiped and no ERROR message will be displayed. In the PHP 4.3.3 and earlier versions, this was not necessary but it is now! ;)

If you want to resize an image proportionally to fit within a given area, like I did, the following code might help you out.

If either hscale or wscale are greater than 1 then that dimension is too big. If you then scale your image by the larger of the two values (hscale, wscale) then you guarantee that both dimensions will now fit in your specified area :)

Using remote files with getimagesize($URL) never worked for me. Except when I would grab files from the same server. However, I developed some code with the help from the people here that does work. If you are having problems give this function a shot:

If you want to show thumbnails keeping the original proportions, with defined maximum width and height, you can use this function. This is useful when showing tables of user-uploaded images, that not necessarily are same-sized. However, for big images (like wallpapers), a better option is to create separated thumbnails with a image-editing software.

If the image is smaller or equal than the defined maximums, then it's showed without resizing. If not, creates a link to a pop-up that shows the full-size image.

$defaultImgWidth would be the target width of the image -- note that the code above resizes the image without distorting its original proportions, and only if it is wider than $defaultImgWidth.the ImageMagick syntax used above ("mogrify ..") overwrites the original file ($uploadName) with the resized image.

For those that like to go the dynamic thumbnail route, I've found that you can get warnings with getimagesize() after your loop through more than 3 to 4 images. In my case I needed 12 images on each page.

Use usleep() in your loop just before you run getimagesize() otherwise you'll end up with warnings, big images and a broken page. Using usleep() lets the server recoup for X milliseconds so it will accept connections again for the image size.

I've found that usleep(1500) is the best for my situation. This barely slows the page down and allows for getimagesize() to work 100% of the time for me.

I figured others have wanted to scale an image to a particular height or width while preserving the height/width ratio. So here are the functions I wrote to accomplish this. Hopefully they'll save somebody else the five minutes it took to write these.

You give the filename and the dimension you want to use, and these functions return the opposite dimension:

For those of you trying to derive the dimensions of a video file (e.g. Video for Windows AVI, Quicktime MOV, MPEG MPG, Windows Media Video WMV or ASF, etc.), you will find the getid3 library to be indispensible. Found at http://getid3.sourceforge.net, here's an example of its use in a script:

You can then use your OBJECT and EMBED tags in HTML to put the video into a web page, and make the PHP template independent of the size parameters of the particular video it happens to be loading. (Just remember to add pixels to the video height to accomodate the controller of the embedded player: typically, 16 pixels for Quicktime, 46 pixels for Windows Media Player 6, and 64 pixels for Windows Media Player 7.

Note that if you specify a remote file (via a URL) to check the size of, PHP will first download the remote file to your server.

If you're using this function to check the size of user provided image links, this could constitute a security risk. A malicious user could potentially link to a very large image file and cause PHP to download it. I do not know what, if any, file size limits are in place for the download. But suppose the user provided a link to an image that was several gigabytes in size?

It would be nice if there were a way to limit the size of the download performed by this function. Hopefully there is already a default with some sensible limits.

I had for quite some time been using getimagesize() to check for the existence of a remote image. This turned out to take way too long. The following curl solution only checks the http headers so it is much more efficient.

***********************************Copies Source Image to Destination Image ***********************************1. Copies source image2. Calculates image dimensions3. Resizes image (you specify max height/width)4. Retains aspect ratio5. Writes destination image***********************************This was created from a variety of code snippets I've found here at php.net and other places on the web. I take no credit for any of this code other than putting the pieces together.