Class: Magick::Image

Inherits:
Object show all
Defined in:
lib/commercebank/monkey.rb

Instance Method Summary collapse

Instance Method Details

#autocrop(red = 65535, green = 65535, blue = 65535) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/commercebank/monkey.rb', line 69

def autocrop(red = 65535, green = 65535, blue = 65535)
  low_x = 0
  low_y = 0
  high_x = columns
  high_y = rows

  croppable = Proc.new do |x, y|
    pixel = pixel_color(x, y)
    (pixel.red == red) && (pixel.green == green) && (pixel.blue == blue)
  end

  # Scan the top horizontal.
  low_y += 1 until (low_y == rows) || (low_x..high_x).find {|x| !croppable.call(x, low_y)}

  # Scan the bottom horizontal.
  high_y -= 1 until (low_y == high_y) || (low_x..high_x).find {|x| !croppable.call(x, high_y)}

  # Scan the left vertical.
  low_x += 1 until (low_x == columns) || (low_y..high_y).find {|y| !croppable.call(low_x, y)}

  # Scan the right vertical.
  high_x -= 1 until (low_x == high_x) || (low_y..high_y).find {|y| !croppable.call(high_x, y)}

  width = high_x - low_x
  height = high_y - low_y

  crop low_x, low_y, width, height
end