Class: RuCaptcha::Captcha

Inherits:
Object
  • Object
show all
Defined in:
lib/rucaptcha/captcha.rb

Class Method Summary collapse

Class Method Details

.create(code) ⇒ Object

Create Captcha image by code



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rucaptcha/captcha.rb', line 19

def create(code)
  size         = "#{RuCaptcha.config.width}x#{RuCaptcha.config.height}"
  font_size    = (RuCaptcha.config.height * 0.8).to_i
  half_width   = RuCaptcha.config.width / 2
  half_height  = RuCaptcha.config.height / 2
  line_color   = rand_color
  chars        = code.split('')
  text_opts    = []
  text_top     = (RuCaptcha.config.height - font_size) / 2
  text_padding = 5
  text_width   = (RuCaptcha.config.width / chars.size) - text_padding * 2
  text_left    = 5

  chars.each_with_index do |char, i|
    text_opts << %(-fill '#{rand_color}' -draw 'text #{(text_left + text_width) * i + text_left},#{text_top} "#{char}"')
  end

  command = "    convert -size \#{size} \#{text_opts.join(' ')}  \\\n    -draw 'stroke \#{line_color} line \#{rand(10)},\#{rand(20)} \#{half_width + rand(half_width)},\#{rand(half_height)}' \\\n    -draw 'stroke \#{line_color} line \#{rand(10)},\#{rand(25)} \#{half_width + rand(half_width)},\#{half_height + rand(half_height)}' \\\n    -draw 'stroke \#{line_color} line \#{rand(10)},\#{rand(30)} \#{half_width + rand(half_width)},\#{half_height + rand(half_height)}' \\\n    -wave \#{rand(2) + 2}x\#{rand(2) + 1} \\\n    -gravity NorthWest -sketch 1x10+\#{rand(1)} -pointsize \#{font_size} -weight 700 \\\n    -implode \#{RuCaptcha.config.implode} label:- png:-\n  CODE\n\n  command.strip!\n  # puts command\n  pid, stdin, stdout, stderr = POSIX::Spawn.popen4(command)\n  Process.waitpid(pid)\n  stdout.read\nend\n"

.rand_colorObject



6
7
8
9
10
# File 'lib/rucaptcha/captcha.rb', line 6

def rand_color
  rgb = [rand(100).to_s(8), rand(100).to_s(8), rand(100).to_s(8)]

  "rgba(#{rgb.join(',')},1)"
end

.random_charsObject



12
13
14
15
16
# File 'lib/rucaptcha/captcha.rb', line 12

def random_chars
  chars = SecureRandom.hex(RuCaptcha.config.len / 2).downcase
  chars.gsub!(/[0ol1]/i, (rand(8) + 2).to_s)
  chars
end