Fast way to get image dimensions (not filesize)

dAnjou picture dAnjou · Jan 12, 2011 · Viewed 94.8k times · Source

I'm looking for a fast way to get the height and width of an image in pixels. It should handle at least JPG, PNG and TIFF, but the more the better. I emphasize fast because my images are quite big (up to 250 MB) and it takes soooo long to get the size with ImageMagick's identify because it obviously reads the images as a whole first.

Preferably, I look for a way that works well in Ruby, or even in Rails 3.

I know the theory stuff (various image formats, their headers and their differences, and so on). Indeed, I ask for some kind of library that can resolve my issue in a fairly generic way.

I just found imagesize which looks promising although development seems to be dead.

Answer

ypnos picture ypnos · Jan 12, 2011
  • The file command prints the dimensions for several image formats (e.g. PNG, GIF, JPEG; recent versions also PPM, WEBP), and does only read the header.

  • The identify command (from ImageMagick) prints lots of image information for a wide variety of images. It seems to restrain itself to reading the header portion (see comments). It also has a unified output which file sadly lacks.

  • exiv2 gives you dimensions for many formats, including JPEG, TIFF, PNG, GIF, WEBP, even if no EXIF header present. It is unclear if it reads the whole data for that though. See the manpage of exiv2 for all supported image formats.

  • head -n1 will give you the dimensions for PPM, PGM formats.

For formats popular on the web, both exiv2 and identify will do the job. Depending on the use-case you may need to write your own script that combines/parses outputs of several tools.