Wednesday, January 31, 2007

Image Size on Ruby

If you need to know the dimensions of an image file in ruby, for example because you want to set the "width" and "height" properties of an image on a web page, here's how to do it:

Start by getting libimage-size. If you're using Ubuntu you can fetch it using sudo apt-get install libimage-size-ruby.

You can now use the ImageSize class to fetch the width and height of your image. There are several ways of doing this, so here's one:

open(image_path) do |fh|
img_size = ImageSize.new(fh)
end
puts "Width: #{img_size.get_width} Height: #{img_size.get_height}"

No comments: