Class: Escpos::ImageProcessors::MiniMagick

Inherits:
Base
  • Object
show all
Defined in:
lib/escpos/image_processors/mini_magick.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 = {}) ⇒ MiniMagick

Returns a new instance of MiniMagick.



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

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

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

  super
end

Instance Method Details

#assert_options!Object



34
35
36
# File 'lib/escpos/image_processors/mini_magick.rb', line 34

def assert_options!
  assert_dimensions_multiple_of_8!
end

#get_pixel(x, y) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/escpos/image_processors/mini_magick.rb', line 23

def get_pixel(x, y)
  @pixels ||= image.get_pixels

  r, g, b =
    @pixels[y][x][0],
    @pixels[y][x][1],
    @pixels[y][x][2]

  (r + b + g) / 3
end

#process!Object



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
81
# File 'lib/escpos/image_processors/mini_magick.rb', line 48

def process!
  if options.fetch(:compose_alpha, false)
    image.combine_options do |c|
      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)
      c.background "rgb(#{bg_r},#{bg_g},#{bg_b})"
      c.flatten
    end
  end

  # Get the first image out of animated gifs
  image.collapse!

  # Optimise more actions to single call
  image.combine_options do |c|
    c.rotate options.fetch(:rotate) if options.has_key?(:rotate)
    c.resize options.fetch(:resize) if options.has_key?(:resize)

    c.grayscale('Rec709Luma') if options.fetch(:grayscale, false)

    if options.fetch(:dither, false)
      c.monochrome '+dither'
      # dither the image with FloydSteinberg algoritm for better results
      c.dither 'FloydSteinberg'
    end
  end

  # Limit the extent of the image to nice round numbers
  if options.fetch(:extent, false)
    image.extent "#{(image.width/8.0).round*8}x#{(image.height/8.0).round*8}"
  end
end

#require_mini_magick!Object

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



41
42
43
44
45
46
# File 'lib/escpos/image_processors/mini_magick.rb', line 41

def require_mini_magick!
  return if defined?(::MiniMagick)
  require "mini_magick"
  rescue LoadError => e
    raise DependencyNotInstalled.new("mini_magick")
end