DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Determine Image Size

10.12.2005
| 30107 views |
  • submit to reddit
        Attributed to Sam Stephenson:
IO.read('image.png')[0x10..0x18].unpack('NN')
=> [713, 54]
Homegrown,

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')

JPEG (slightly more complex):
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
  end

private
  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
  end
end
From my blog entry about <a href="http://blog.remvee.net/post/13">reading JPEG</a>.    

Comments

Snippets Manager replied on Fri, 2008/09/19 - 1:07pm

This is great! I can quickly check the size of an image without having to install an image manipulation library.

Snippets Manager replied on Tue, 2007/01/09 - 7:02pm

For those who want to use libimage-size-ruby1.8 on a Windows machine, simply copy 'image_size.rb', installed from the package (mine was in /usr/lib/ruby/1.8), and paste it in your C:\RUBY_ROOT\lib\1.8\ directory (mine was C:\ruby\lib\1.8\). It is, after all, a 100% Ruby extension so it should work on any OS that supports Ruby. Worked like a charm!

Snippets Manager replied on Tue, 2006/09/19 - 10:46am

on debian based (ubuntu) just use $ sudo apt-get install libimage-size-ruby1.8

Snippets Manager replied on Mon, 2012/05/07 - 2:15pm

Love it!