class Bitmap attr_reader :filename, :file, :magic, :file_size, :pixel_width, :pixel_height, :bmp_data, :full_data, :bmp_size, :bits_per_pixel def initialize(filename) @filename = filename @file = open("#{@filename}", "rb") @full_data = [] @bmp_data = [] temp_index = 0 @file.each_byte do |byte| t = to_hex(byte) if t.length == 1 then t = "0" + t end @full_data[temp_index] = t temp_index += 1 end @file.close @magic = @full_data[0..1].to_s if @magic != "424d" then print "Oh heck, the magic number is wrong -- things may be wacky!" end @file_size = @full_data[2..5].reverse.to_s.hex @app1 = @full_data[6..7].to_s @app2 = @full_data[8..9].to_s @bmp_offset = @full_data[10..13].reverse.to_s.hex @header_size = @full_data[14..17].reverse.to_s.hex @pixel_width = @full_data[18..21].reverse.to_s.hex @pixel_height = @full_data[22..25].reverse.to_s.hex @color_planes = @full_data[26..27].reverse.to_s.hex @bits_per_pixel = @full_data[28..29].reverse.to_s.hex @compression = @full_data[30..33].reverse.to_s.hex @bmp_size = @full_data[34..37].reverse.to_s.hex @horizontal_resolution = @full_data[38..41].reverse.to_s.hex @vertical_resolution = @full_data[42..45].reverse.to_s.hex @palette_size = @full_data[46..49].reverse.to_s.hex @important_colours = @full_data[50..53].reverse.to_s.hex 0.upto(@pixel_height-1) do |height| @bmp_data[height] = @full_data[(54+(height*@pixel_width*@bits_per_pixel/8)) .. ((54+(height*@pixel_width*@bits_per_pixel/8))+(@pixel_width*@bits_per_pixel/8))-1] end end def convert_small_hex(num) if num.class == Fixnum then if num < 0 or num > 15 then "error" elsif num <= 9 then num.to_s else (num+87).chr end end end def to_hex(num) str = "" if num < 16 then convert_small_hex(num) else str += to_hex(num/16).to_s str += convert_small_hex(num - (num/16 * 16)) end end def show_bmp @bmp_data.each do |line| puts line.to_s end end def show_bmp_pixelate @bmp_data.each do |line| count = 0 line.each do |b| print b count += 1 if count == 3 then print " " count = 0 end end puts end end end b = Bitmap.new("test.bmp") puts "Showing bitdump:" b.show_bmp puts puts "Showing bitdump with pixel-aligned spaces:" b.show_bmp_pixelate