Module: SimpleBMP
- Defined in:
- lib/simple_bmp.rb
Overview
Currently there are no need of classes – just a single public module method.
Class Method Summary collapse
-
.export(pixels, filename = "temp.bmp") ⇒ Object
Pixels is either two or three dimensional array: pixels: [height x width x 3] of 0..255 for RGB pixels: [height x width] of 0..255 for grayscale Two-dimensional will be processed as it’s three, where R, G anb B are equal.
Class Method Details
.export(pixels, filename = "temp.bmp") ⇒ Object
Pixels is either two or three dimensional array:
pixels: [height x width x 3] of 0..255 for RGB
pixels: [height x width] of 0..255 for grayscale
Two-dimensional will be processed as it’s three, where R, G anb B are equal.
Examples of exporting a single pixel image which is almost gray:
export [[100]], "temp.bmp"
export [[[90,100,110]]], "temp.bmp"
– we use BITMAPINFOHEADER (40 bytes), because BITMAPCOREHEADER (12 bytes) can’t 1 channel
19 20 21 22 23 24 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 60 |
# File 'lib/simple_bmp.rb', line 19 def self.export pixels, filename = "temp.bmp" bitmap_width = pixels.first.size bitmap_height = pixels.size =begin -- hsv2bgr = lambda do |(h,s,v)| a = (v - vmin = (100-s)*v/100)*(h % 60)/60.0 vinc, vdec = vmin + a, v - a case h/60 when 0 ; [vmin, vinc, v] when 1 ; [vmin, v, vdec] when 2 ; [vinc, v, vmin] when 3 ; [v, vdec, vmin] when 4 ; [v, vmin, vinc] when 5 ; [vdec, vmin, v] end.map{ |i| (2.55 * i).floor } end =end pixel_array = pixels.reverse.flat_map do |row| #-- # row_bytes = row.map(&hsv2bgr).flatten row_bytes = row.flat_map{ |pixel| pixel.is_a?(Array) ? pixel : [pixel]*3 } row_bytes.fill 0, row_bytes.size .. (row_bytes.size + 3) / 4 * 4 - 1 end #-- # 12=>BITMAPCOREHEADER, 40=>BITMAPINFOHEADER dib_header_size = 12 file_size = 14 + dib_header_size + pixel_array.size open(filename, "wb") do |file| #-- # Bitmap file header file.write ["BM", file_size, 14 + dib_header_size].pack "A2qi" # "A2QL" #-- # DIB header # file.write [dib_header_size, bitmap_width, bitmap_height, 1, 24].pack "LllSS" # file.write [0, 0, 1, 1, 0, 0].pack "LLllLL" file.write [dib_header_size, bitmap_width, bitmap_height, 1, 24].pack "LSSSS" file.write pixel_array.pack "C*" end end |