Sha256: a856eff411fec6d9eb8ea0e24624831a0ffa07c3d3ff6fa794eaaa141067b198

Contents?: true

Size: 1.66 KB

Versions: 4

Compression:

Stored size: 1.66 KB

Contents

module ChocBomb
  module Tools
    module Images
      def self.size(file)
        if File.extname(file) == ".png"
          png(file)
        else
          jpeg(file)
        end
      end
      
      def self.png(file)
        IO.read(file)[0x10..0x18].unpack('NN')
      end
      
      def self.jpeg(file)
        j = JPEG.new(file)
        [j.width, j.height]
      end
      
      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
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
chocbomb-0.0.3 lib/chocbomb/tools/images.rb
chocbomb-0.0.2 lib/chocbomb/tools/images.rb
chocbomb-0.0.1 lib/chocbomb/tools/images.rb
chocbomb-0.0.0 lib/chocbomb/tools/images.rb