-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaptcha.rb
56 lines (44 loc) · 1.33 KB
/
captcha.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
52
53
54
55
56
require 'rmagick'
class Captcha
# Generates the CAPTCHA image with +captcha_text+
# @param [String] captcha_text the text to include in the CAPTCHA image
# @return [String] the bytes of the generated image
def self.generate(captcha_text, width = 100, height = 32, text_size = 22)
image = create_image(width, height)
draw_text!(captcha_text, image, text_size)
image = apply_distortion!(image)
data = image.to_blob
image.destroy!
data
end
def self.create_image(width, height)
image = Magick::Image.new(width, height)
image.format = 'jpg'
image.gravity = Magick::CenterGravity
image.background_color = 'white'
image
end
def self.draw_text!(text, image, text_size)
draw = Magick::Draw.new
draw.annotate(image, image.columns, image.rows, 0, 0, text) do
self.gravity = Magick::CenterGravity
self.pointsize = text_size
self.fill = 'darkblue'
self.stroke = 'transparent'
end
nil
end
def self.apply_distortion!(image)
image = image.wave *random_wave_distortion
image = image.implode random_implode_distortion
image = image.swirl rand(10)
image = image.add_noise Magick::ImpulseNoise
image
end
def self.random_wave_distortion
[2 + rand(2), 40 + rand(20)]
end
def self.random_implode_distortion
(2 + rand(2)) / 20.0
end
end