Class: ImageRuby::BmpDecoder

Inherits:
Decoder
  • Object
show all
Defined in:
lib/imageruby-bmp.rb

Instance Method Summary collapse

Instance Method Details

#decode(data, image_class) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/imageruby-bmp.rb', line 25

def decode(data, image_class)

  # read bmp header
  header = data[0..13]
  dib_header = data[14..54]

  magic = header[0..1]

  # check magic
  unless magic == "BM"
    raise UnableToDecodeException
  end

  pixeldata_offset = header[10..13].unpack("L").first

  width = dib_header[4..7].unpack("L").first
  height = dib_header[8..11].unpack("L").first

  # create image object

  image = image_class.new(width,height)

  padding_size = ( 4 - (width * 3 % 4) ) % 4
  width_array_len = width*3 + padding_size

  # read pixel data
  height.times do |y|
    offset = pixeldata_offset+(height-y-1)*width_array_len
    index = (y*width)*3
    image.pixel_data[index..index+width*3] = data[offset..offset+width*3]
  end

  image

end