class SimpleCaptchaReloaded::Image

Constants

DISTORTIONS
IMAGE_STYLES
IMPLODES

Public Class Methods

new(implode: :medium, distortion: :medium, image_styles: IMAGE_STYLES.slice('simply_red', 'simply_green', 'simply_blue'), noise: 1, size: '100x28', image_magick_path: '') click to toggle source
# File lib/simple_captcha_reloaded/image.rb, line 30
def initialize(implode: :medium,
               distortion: :medium,
               image_styles: IMAGE_STYLES.slice('simply_red', 'simply_green', 'simply_blue'),
               noise: 1,
               size: '100x28',
               image_magick_path: '')

  @implode           = implode
  @distortion        = distortion
  if !DISTORTIONS.keys.include?(@distortion)
    @distortion = DISTORTIONS.keys.sample
  end
  @distortion_function = DISTORTIONS[@distortion]
  @image_styles      = image_styles
  @noise             = noise
  @size              = size
  @image_magick_path = image_magick_path
end

Public Instance Methods

generate(text) click to toggle source
# File lib/simple_captcha_reloaded/image.rb, line 49
def generate(text)
  amplitude, frequency = calculate_distortion

  params = image_params.dup
  params << "-size #{@size}"
  params << "-wave #{amplitude}x#{frequency}"
  params << "-gravity Center"
  params << "-pointsize 22"
  params << "-implode #{IMPLODES[@implode]}"
  params << "label:#{text}"
  params << "-evaluate Uniform-noise #{@noise}"
  params << "jpeg:-"
  run("convert", params: params.join(' '))
end

Protected Instance Methods

calculate_distortion() click to toggle source
# File lib/simple_captcha_reloaded/image.rb, line 70
def calculate_distortion
  @distortion_function.call()
end
image_params() click to toggle source
# File lib/simple_captcha_reloaded/image.rb, line 66
def image_params
  @image_styles.values.sample
end
run(cmd, params: "", count: 0) click to toggle source
# File lib/simple_captcha_reloaded/image.rb, line 74
def run(cmd, params: "", count: 0)
  command = %Q[#{cmd} #{params}].gsub(/\s+/, " ")
  command = "#{command} 2>&1"
  unless (image_magick_path = @image_magick_path).blank?
    command = File.join(image_magick_path, command)
  end
  output = nil
  Timeout::timeout(SimpleCaptchaReloaded::Config.timeout) {
    output = `#{command}`
  }
  unless $?.success?
    raise SimpleCaptchaReloaded::Error, "Error while running #{command}\n Exit Code: #{$?}\n stdout:#{output.inspect}"
  end
  output
rescue Timeout::Error
  if count > 3
    run(cmd, params: params, count: count + 1)
  else
    raise SimpleCaptchaReloaded::Error, "Error while running #{command} #{count + 1} times. Timed out after #{SimpleCaptchaReloaded::Config.timeout} seconds."
  end
end