Created
December 5, 2009 21:53
-
-
Save max-mapper/249877 to your computer and use it in GitHub Desktop.
lists images in a directory, returns javascript array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pow' | |
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 | |
class ImageList | |
attr_reader :images | |
def initialize | |
scan | |
end | |
def scan | |
basedir = "images/gallery/" | |
path = Pow(basedir) | |
@images = "[\n" | |
path.files.each do |document| | |
case document.extention | |
when /png/i then dimensions = IO.read(basedir + document.name)[0x10..0x18].unpack('NN') | |
when /gif/i then dimensions = IO.read(basedir + document.name)[6..10].unpack('SS') | |
when /bmp/i then bmp = IO.read(basedir + document.name)[14..28] | |
dimensions = bmp[0] == 40 ? bmp[4..-1].unpack('LL') : bmp[4..8].unpack('SS') | |
when /jpe?g/i then dimensions = [] | |
dimensions[0] = JPEG.new(basedir + document.name).height | |
dimensions[1] = JPEG.new(basedir + document.name).width | |
end | |
if dimensions | |
@images += "[\'#{basedir}#{document.name}\', \'#{document.name(false)}\', \'#{dimensions[0]}\', \'#{dimensions[1]}\'],\n" | |
end | |
end | |
@images.chop!.chop! unless @images == "[\n" | |
@images += "\n];\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment