Class: Img2Zpl::Image

Inherits:
MiniMagick::Image
  • Object
show all
Defined in:
lib/img2zpl/image.rb

Instance Method Summary collapse

Instance Method Details

#to_zpl(black_threshold: 0.5, invert: false, compress: true) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/img2zpl/image.rb', line 7

def to_zpl(black_threshold: 0.5, invert: false, compress: true)
  bytes_per_row = (width % 8).positive? ? (width / 8) + 1 : (width / 8)
  byte_count = bytes_per_row * height
  data, line, previous_line, byte = Array.new(4) { +"" }

  get_pixels.each do |row|
    row.each_with_index do |column, i|
      r, g, b = column.map(&:to_i)
      b_dot, w_dot = invert ? %w[1 0] : %w[0 1]
      byte << (((r + g + b) > (black_threshold * 765)) ? b_dot : w_dot)

      if ((i + 1) % 8).zero? || i == (width - 1)
        line_str = byte.ljust(8, "0").to_i(2).to_s(16).upcase.rjust(2, "0")
        line << line_str
        byte = +""
      end
    end

    data << if compress
      ((line == previous_line) ? ":" : line.gsub(/0+$/, ",").gsub(/F+$/, "!"))
    else
      line
    end

    previous_line = line
    line = +""
  end

  _compress(data) if compress
  "^GFA,#{byte_count},#{byte_count},#{bytes_per_row},#{data}^FS"
end