Module: ZPNG::BMP::Reader

Included in:
Image
Defined in:
lib/zpng/bmp/reader.rb

Instance Method Summary collapse

Instance Method Details

#_read_bmp(io) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/zpng/bmp/reader.rb', line 157

def _read_bmp io
  fhdr = BITMAPFILEHEADER.read(io)
  # DIB Header immediately follows the Bitmap File Header
  ihdr = BITMAPINFOHEADER.read(io)
  if ihdr.biSize != BITMAPINFOHEADER::SIZE
    raise "dib_hdr_size #{ihdr.biSize} unsupported, want #{BITMAPINFOHEADER::SIZE}"
  end

  @new_image = true
  @color_class = BMP::Color
  @format = :bmp
  @chunks << BmpPseudoChunk.new(fhdr)
  @chunks << BmpHdrPseudoChunk.new(ihdr)

  # http://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage
  row_size = ((ihdr.biBitCount*self.width+31)/32)*4

  gap1_size = fhdr.bfOffBits - io.tell

  STDERR.puts "[?] negative gap1=#{gap1_size}".red if gap1_size < 0

  if ihdr.biBitCount == 8 && gap1_size >= 1024
    # palette for 256-color BMP
    data = io.read 1024
    @chunks << BmpPaletteChunk.new(data)
    gap1_size -= 1024
  end

  if gap1_size != 0
    @chunks << BmpPseudoChunk.new(
      TypedBlock.new("GAP1", gap1_size, io.tell, io.read(gap1_size))
    )
    #io.seek(fhdr.bfOffBits)
  end

  pos0 = io.tell
  @scanlines = []
  self.height.times do |idx|
    offset = io.tell - fhdr.bfOffBits
    data = io.read(row_size)
    # BMP scanlines layout is upside-down
    @scanlines.unshift ScanLine.new(self, self.height-idx-1,
                                    :decoded_bytes => data,
                                    :size   => row_size,
                                    :offset => offset
                                   )
  end

  @chunks << BmpPseudoChunk.new(
      TypedBlock.new("IMAGEDATA", io.tell - pos0, pos0, '')
  )

  unless io.eof?
    @chunks << BmpPseudoChunk.new(
      TypedBlock.new("GAP2", io.size - io.tell, io.tell, '')
    )
  end

  extend ImageMixin
end