Skip to content

Instantly share code, notes, and snippets.

@remvee
Created May 1, 2010 09:36
Show Gist options
  • Save remvee/386188 to your computer and use it in GitHub Desktop.
Save remvee/386188 to your computer and use it in GitHub Desktop.
read jpeg till width and height are known
def examine(io)
class << io
def readbyte; readchar; end unless method_defined?(:readbyte)
def readint; (readbyte << 8) + readbyte; end
def readframe; read(readint - 2); end
def readsof; [readint, readbyte, readint, readint, readbyte]; end
def next
c = readbyte while c != 0xFF
c = readbyte while c == 0xFF
c
end
end
raise 'malformed JPEG' unless io.readbyte == 0xFF && io.readbyte == 0xD8 # SOI
height = width = nil
while marker = io.next
case marker
when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF # SOF markers
length, _, height, width, components = io.readsof
break
when 0xD9, 0xDA
break # EOI, SOS
else
io.readframe # ignore frame
end
end
[width, height]
end
ARGV.each do |fname|
File.open(fname) do |f|
puts "#{fname}: #{examine(f).join('x')} (after reading #{f.pos} bytes)"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment