Module: Jcaptcha

Defined in:
lib/jcaptcha.rb,
lib/jcaptcha/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.create(code) ⇒ Object

Create Captcha image by code



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/jcaptcha.rb', line 23

def create(code)
  chars        = code.split('')
  all_left     = 20
  font_size    = 45
  full_height  = font_size
  full_width   = font_size * chars.size
  size         = "#{full_width}x#{full_height}"
  half_width   = full_width / 2
  text_top     = 0
  text_left    = 0 - (font_size * 0.28).to_i
  stroke_width = (font_size * 0.05).to_i + 1
  text_width   = font_size + text_left
  text_opts    = []
  line_opts    = []

  chars.each_with_index do |char, i|
    rgb = random_color
    text_color = "rgba(#{rgb.join(',')}, 1)"
    line_color = "rgba(#{rgb.join(',')}, 0.6)"
    text_opts << %(-fill '#{text_color}' -draw 'text #{(text_left + text_width) * i + all_left},#{text_top} "#{char}"')
    left_y = rand_line_top(text_top, font_size)
    right_x = half_width + (half_width * 0.3).to_i
    right_y = rand_line_top(text_top, font_size)
    line_opts << %(-draw 'stroke #{line_color} line #{rand(10)},#{left_y} #{right_x},#{right_y}')
  end

  command = "    convert -size \#{size} \\\n    -strokewidth \#{stroke_width} \\\n    \#{line_opts.join(' ')} \\\n    -pointsize \#{font_size} -weight 500 \\\n    \#{text_opts.join(' ')}  \\\n    -wave \#{rand(2) + 3}x\#{rand(2) + 1} \\\n    -rotate \#{rand(10) - 5} \\\n    -gravity NorthWest -sketch 1x10+\#{rand(2)} \\\n    -fill none \\\n    -implode 0.3 -trim label:- png:-\n  CODE\n\n  command.strip!\n  out, err, _st = Open3.capture3(command)\n  raise \"RuCaptcha: \#{err.strip}\" if err.present?\n  out\nend\n"

.rand_line_top(text_top, font_size) ⇒ Object



18
19
20
# File 'lib/jcaptcha.rb', line 18

def rand_line_top(text_top, font_size)
  text_top + rand(font_size * 0.7).to_i
end

.random_colorObject



8
9
10
11
12
# File 'lib/jcaptcha.rb', line 8

def random_color
  color = [random_color_seed, random_color_seed, random_color_seed]
  color[rand(3)] = 0.to_s(8)
  color
end

.random_color_seedObject



14
15
16
# File 'lib/jcaptcha.rb', line 14

def random_color_seed
  (rand(150) + 10).to_s(8)
end