Module: CustomCaptcha::Image

Defined in:
lib/custom_captcha/image.rb

Constant Summary collapse

@@image_style =
{
  :simply_blue => {:background_color => :white, :text_fill => :darkblue, :text_font_family => :helvetica}
}
@@font_size =

image text length and image text font_size proportion

{
  4 => 46,
  5 => 41,
  6 => 36,
  7 => 31,
  8 => 26,
  9 => 21,
  10 => 16
}

Class Method Summary collapse

Class Method Details

.create(number = 1, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/custom_captcha/image.rb', line 19

def create(number=1, &block)
  image_style_simply_blue = @@image_style[:simply_blue]
  image_style = @@image_style[CustomCaptcha::Configuration.image_style] || image_style_simply_blue
  options = {}
  options[:background_color] = image_style[:background_color] || image_style_simply_blue[:background_color]
  options[:text_fill] = image_style[:text_fill] || image_style_simply_blue[:text_fill]
  options[:text_font_family] = image_style[:text_font_family] || image_style_simply_blue[:text_font_family]
  image_files = create_image_files(number, options, &block)
end

.create_image_files(number, options = {}, &block) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/custom_captcha/image.rb', line 48

def create_image_files(number, options={}, &block)
  columns = CustomCaptcha::Configuration.image_columns
  rows = CustomCaptcha::Configuration.image_rows

  image_files = []
  number.to_i.times do |n|
    canvas = Magick::ImageList.new
    canvas.new_image(columns, rows) {
      self.background_color = options[:background_color].to_s
    }
    text = Magick::Draw.new
    text.font_family = options[:text_font_family].to_s
    text.fill = options[:text_fill].to_s
    text.gravity = Magick::CenterGravity

    image_text = generate_image_text()
    text.annotate(canvas, 0,0,0,0, image_text) {
      self.pointsize = @@font_size[image_text.length]
    }
    image_file = generate_image_file_path(image_text)
    begin
      canvas.write(image_file)
    rescue
      yield(number, n+1, "failed", image_file) if block
      next
    else
      yield(number, n+1, "succeed", image_file) if block
      image_files << image_file
    ensure
      canvas.clear
    end
  end
  image_files
end

.generate_image_file_path(text) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/custom_captcha/image.rb', line 38

def generate_image_file_path(text)
  File.join(
    CustomCaptcha::Utils.image_file_dirname(),
    [
      CustomCaptcha::Utils.image_file_basename(text),
      CustomCaptcha::Utils.image_file_extname()
    ].join()
  )
end

.generate_image_textObject



32
33
34
35
36
# File 'lib/custom_captcha/image.rb', line 32

def generate_image_text
  text_range = CustomCaptcha::Configuration.text_range
  text_length = CustomCaptcha::Configuration.text_length
  text_range.to_a.sort_by!{rand()}.take(text_length).join()
end