Class: Kamcaptcha::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/kamcaptcha/generator.rb

Defined Under Namespace

Classes: DictionaryWordGenerator, RandomWordGenerator, WordGenerator

Constant Summary collapse

DEFAULTS =
{
  :width  => 240,
  :height => 50,
  :length => 5,
  :format => "png",
  :count  => 1
}

Class Method Summary collapse

Class Method Details

.build_image(word, width, height) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/kamcaptcha/generator.rb', line 104

def self.build_image(word, width, height)
  text_img  = Magick::Image.new(width, height)
  black_img = Magick::Image.new(width, height) do
    self.background_color = "black"
  end

  text_img.annotate(Magick::Draw.new, 0, 0, 0, 0, word) do
    self.gravity      = Magick::WestGravity
    self.font_family  = "Verdana"
    self.font_weight  = Magick::BoldWeight
    self.fill         = "#666666"
    self.stroke       = "black"
    self.stroke_width = 2
    self.pointsize    = 44
  end

  # Apply a little blur and fuzzing
  text_img        = text_img.gaussian_blur(1.2, 1.2)
  text_img        = text_img.sketch(20, 30.0, 30.0)
  text_img        = text_img.wave(3, 90)

  # Now we need to get the white out
  text_mask       = text_img.negate
  text_mask.matte = false

  # Add cut-out our captcha from the black image with varying tranparency
  black_img.composite!(text_mask, Magick::CenterGravity, Magick::CopyOpacityCompositeOp)

  text_img.destroy!
  text_mask.destroy!

  black_img
end

.generate(path, options = {}) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/kamcaptcha/generator.rb', line 78

def self.generate(path, options = {})
  options = DEFAULTS.merge(options)

  if options[:source] != "random"
    source = DictionaryWordGenerator.new(options[:length])
  else
    source = RandomWordGenerator.new(options[:length])
  end

  files = []

  options[:count].times do
    word  = source.generate
    image = build_image(word, options[:width], options[:height])
    name  = word.delete(" ").downcase
    file  = File.join(path, Kamcaptcha.encrypt(name) + ".#{options[:format]}")

    image.write(file)
    image.destroy!

    files << file
  end

  files
end