Module: ImageGenerator

Extended by:
ImageGenerator
Included in:
ImageGenerator
Defined in:
lib/captcha3/image_generator.rb

Constant Summary collapse

BITS =
("A".."Z").to_a + (0..9).to_a
BIT_LENGTH =
BITS.length
DEFAULT_PARAS =
{
	:image_width => 150,
	:image_height => 50,
	:captcha_length => 5,
	:file_type => 'png'
}

Instance Method Summary collapse

Instance Method Details

#generate_captcha_image(params = {}) ⇒ Object



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
# File 'lib/captcha3/image_generator.rb', line 14

def generate_captcha_image(params = {})
	params.reverse_merge!(DEFAULT_PARAS)	
	file_type = %w(png gif).include?(params[:file_type]) ? ".#{params[:file_type]}" : ".png"

	text_img = Magick::Image.new(params[:image_width].to_i, params[:image_height].to_i)
	black_img = Magick::Image.new(params[:image_width].to_i, params[:image_height].to_i) do
		self.background_color = 'black'
	end

	random_string = params[:captcha_length].times.map{ BITS[rand(BIT_LENGTH)]}.join

	filename = CaptchaUtil.encrypt_string(random_string.downcase) + file_type

	# Render the text in the image
	text_img.annotate(Magick::Draw.new, 0,0,0,0, random_string) {
		self.gravity = Magick::WestGravity
		self.font_family = 'Courier-New'
		self.font_weight = Magick::BoldWeight
   	self.fill = '#000000'
  	self.stroke = 'black'
		self.stroke_width = 1
  	self.pointsize = 44
	}

  # 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)

	# Write the file to disk
  puts 'Writing image file ' + filename
	black_img.write(filename) # { self.depth = 8 }

  # Collect rmagick
	GC.start
end