Class: Escpos::ImageProcessors::ChunkyPng

Inherits:
Base
  • Object
show all
Defined in:
lib/escpos/image_processors/chunky_png.rb

Instance Attribute Summary

Attributes inherited from Base

#image, #options

Instance Method Summary collapse

Methods inherited from Base

#assert_dimensions_multiple_of_8!

Constructor Details

#initialize(image_or_path, options = {}) ⇒ ChunkyPng

Returns a new instance of ChunkyPng.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/escpos/image_processors/chunky_png.rb', line 7

def initialize(image_or_path, options = {})
  require_chunky_png!

  @image = begin
    if image_or_path.is_a?(ChunkyPNG::Image)
      image_or_path
    elsif image_or_path.is_a?(String)
      ChunkyPNG::Image.from_file(image_or_path)
    else
      raise InputNotSupported
    end
  end

  super
end

Instance Method Details

#assert_options!Object



23
24
25
# File 'lib/escpos/image_processors/chunky_png.rb', line 23

def assert_options!
  assert_dimensions_multiple_of_8!
end

#get_pixel(x, y) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/escpos/image_processors/chunky_png.rb', line 37

def get_pixel(x, y)
  px = image.get_pixel x, y
  r, g, b =
    ChunkyPNG::Color.r(px),
    ChunkyPNG::Color.g(px),
    ChunkyPNG::Color.b(px)

  (r + b + g) / 3
end

#process!Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/escpos/image_processors/chunky_png.rb', line 47

def process!
  extent = options.fetch(:extent, false)
  compose_alpha = options.fetch(:compose_alpha, false)
  grayscale = options.fetch(:extent, false)

  if extent
    new_width = (image.width / 8.0).round * 8
    new_height = (image.height / 8.0).round * 8
    image.resample_nearest_neighbor!(new_width, new_height)
  end

  return if !compose_alpha && !grayscale

  if compose_alpha
    bg_r, bg_g, bg_b =
      options.fetch(:compose_alpha_bg_r, 255),
      options.fetch(:compose_alpha_bg_g, 255),
      options.fetch(:compose_alpha_bg_b, 255)
  end

  0.upto(image.height - 1) do |y|
    0.upto(image.width - 1) do |x|
      px = image.get_pixel(x, y)
      if compose_alpha
        bg_color = ChunkyPNG::Color.rgb(bg_r, bg_g, bg_b)
        px = ChunkyPNG::Color.compose_quick(px, bg_color)
      end
      if grayscale
        px = ChunkyPNG::Color.to_grayscale(px)
      end
      image.set_pixel(x, y, px)
    end
  end
end

#require_chunky_png!Object

ChunkyPng gem is not required intentionally This makes the gem more lightweight by making dependencies optional and based on chosen image processor



30
31
32
33
34
35
# File 'lib/escpos/image_processors/chunky_png.rb', line 30

def require_chunky_png!
  return if defined?(::ChunkyPng)
  require "chunky_png"
  rescue LoadError => e
    raise DependencyNotInstalled.new("chunky_png")
end