Class: Pura::Bmp::Encoder
- Inherits:
-
Object
- Object
- Pura::Bmp::Encoder
- Defined in:
- lib/pura/bmp/encoder.rb
Class Method Summary collapse
Instance Method Summary collapse
- #encode ⇒ Object
-
#initialize(image) ⇒ Encoder
constructor
A new instance of Encoder.
Constructor Details
#initialize(image) ⇒ Encoder
Returns a new instance of Encoder.
13 14 15 |
# File 'lib/pura/bmp/encoder.rb', line 13 def initialize(image) @image = image end |
Class Method Details
.encode(image, output_path) ⇒ Object
6 7 8 9 10 11 |
# File 'lib/pura/bmp/encoder.rb', line 6 def self.encode(image, output_path) encoder = new(image) data = encoder.encode File.binwrite(output_path, data) data.bytesize end |
Instance Method Details
#encode ⇒ Object
17 18 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 61 62 63 64 |
# File 'lib/pura/bmp/encoder.rb', line 17 def encode width = @image.width height = @image.height pixels = @image.pixels stride = ((width * 3) + 3) & ~3 # Row size padded to 4-byte boundary padding = stride - (width * 3) pixel_data_size = stride * height file_size = 14 + 40 + pixel_data_size # File header + info header + pixel data pixel_offset = 14 + 40 out = String.new(encoding: Encoding::BINARY, capacity: file_size) # File header (14 bytes) out << "BM" out << [file_size].pack("V") out << [0, 0].pack("vv") # Reserved out << [pixel_offset].pack("V") # Info header (BITMAPINFOHEADER, 40 bytes) out << [40].pack("V") # Header size out << [width].pack("V") # Width out << [height].pack("l<") # Height (positive = bottom-up) out << [1].pack("v") # Planes out << [24].pack("v") # Bit depth out << [0].pack("V") # Compression (BI_RGB) out << [pixel_data_size].pack("V") # Image size out << [2835].pack("l<") # X pixels per meter (~72 DPI) out << [2835].pack("l<") # Y pixels per meter (~72 DPI) out << [0].pack("V") # Colors used out << [0].pack("V") # Colors important # Pixel data (bottom-to-top, BGR order) pad_bytes = "\x00".b * padding (height - 1).downto(0) do |y| row_offset = y * width * 3 width.times do |x| off = row_offset + (x * 3) r = pixels.getbyte(off) g = pixels.getbyte(off + 1) b = pixels.getbyte(off + 2) out << b.chr << g.chr << r.chr # BGR order end out << pad_bytes if padding.positive? end out end |