Is there a simple way to get image dimensions in Ruby? Is there a simple way to get image dimensions in Ruby? ruby ruby

Is there a simple way to get image dimensions in Ruby?


As of June 2012, FastImage which "finds the size or type of an image given its uri by fetching as little as needed" is a good option. It works with local images and those on remote servers.

An IRB example from the readme:

require 'fastimage'FastImage.size("http://stephensykes.com/images/ss.com_x.gif")=> [266, 56]  # width, height

Standard array assignment in a script:

require 'fastimage'size_array = FastImage.size("http://stephensykes.com/images/ss.com_x.gif")puts "Width: #{size_array[0]}"puts "Height: #{size_array[1]}"

Or, using multiple assignment in a script:

require 'fastimage'width, height = FastImage.size("http://stephensykes.com/images/ss.com_x.gif")puts "Width: #{width}"puts "Height: #{height}"


You could try these (untested):

http://snippets.dzone.com/posts/show/805

PNG:

IO.read('image.png')[0x10..0x18].unpack('NN')=> [713, 54]

GIF:

IO.read('image.gif')[6..10].unpack('SS')=> [130, 50]

BMP:

d = IO.read('image.bmp')[14..28]d[0] == 40 ? d[4..-1].unpack('LL') : d[4..8].unpack('SS')

JPG:

class JPEG  attr_reader :width, :height, :bits  def initialize(file)    if file.kind_of? IO      examine(file)    else      File.open(file, 'rb') { |io| examine(io) }    end  endprivate  def examine(io)    raise 'malformed JPEG' unless io.getc == 0xFF && io.getc == 0xD8 # SOI    class << io      def readint; (readchar << 8) + readchar; end      def readframe; read(readint - 2); end      def readsof; [readint, readchar, readint, readint, readchar]; end      def next        c = readchar while c != 0xFF        c = readchar while c == 0xFF        c      end    end    while marker = io.next      case marker        when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF # SOF markers          length, @bits, @height, @width, components = io.readsof          raise 'malformed JPEG' unless length == 8 + components * 3        when 0xD9, 0xDA:  break # EOI, SOS        when 0xFE:        @comment = io.readframe # COM        when 0xE1:        io.readframe # APP1, contains EXIF tag        else              io.readframe # ignore frame      end    end  endend


There's also a new (July 2011) library that wasn't around at the time the question was originally asked: the Dimensions rubygem (which seems to be authored by the same Sam Stephenson responsible for the byte-manipulation techniques also suggested here.)

Below code sample from project's README

require 'dimensions'Dimensions.dimensions("upload_bird.jpg")  # => [300, 225]Dimensions.width("upload_bird.jpg")       # => 300Dimensions.height("upload_bird.jpg")      # => 225