rmagick 生成验证码

require 'rubygems'
require 'RMagick'
include Magick
class Captcha
  RADIUS = 15
  WIDTH = 100
  HEIGHT = 50
  COLOR = %w{blue yellow red white black rgb(143,143,1433) rgb(179,98,33) rgb(255,207,67) rgb(217,125,219) rgb(128,201,8)}
  def self.draw_captcha()
    center_x = rand((WIDTH-2*RADIUS))+RADIUS
    center_y = rand((HEIGHT-2*RADIUS))+RADIUS
    gc = Magick::Draw.new
    map_gd = Magick::Image.read("public/images/captcha.gif").first
    gc.fill_opacity(0)
    arr = sample(COLOR.size-1,5)
    #    j = i = rand(COLOR.size)
    gc.stroke(COLOR[arr[0]]).stroke_width(2)
    x =rand(80)
    y = rand(30)
    gc.rectangle(x,y,x+20, y+20)
    #    i = rand(COLOR.size)
    gc.stroke(COLOR[arr[1]]).stroke_width(2)
    x = rand(60)
    y= rand(20)
    gc.polygon(x+20,y,x+5,y+10,x+20,y+20,x+35,y+10)

    gc.stroke(COLOR[arr[2]]).stroke_width(2)
    x = rand(60)
    y = rand(30)
    gc.polygon(x,y,x+15, y+20,x+28,y+5)

    gc.stroke(COLOR[arr[3]]).stroke_width(2)
    x = rand(70)
    y = rand(30)
    x =12 if x<10
    y =12 if y<10
    gc.circle(x,y, x+8, y+8)
    gc.stroke(COLOR[arr[4]]).stroke_width(2)
    #    gc.arc(60,10,90,40, 0, 150)
    #    gc.arc(60,10,90,40, 180, 270)
    gc.arc(center_x-RADIUS,center_y-RADIUS,center_x+RADIUS,center_y+RADIUS,60,120)
    gc.arc(center_x-RADIUS,center_y-RADIUS,center_x+RADIUS,center_y+RADIUS,180,240)
    gc.arc(center_x-RADIUS,center_y-RADIUS,center_x+RADIUS,center_y+RADIUS,300,350)
    gc.draw(map_gd)

    return map_gd.to_blob{self.format="JPG"},center_x,center_y
  end

  def self.parse_captcha(x,y,center_x,center_y,player)
    x_ =(center_x -x)*(center_x-x)
    y_ = (center_y-y)*(center_y-y)
    distance = Math.sqrt(x_+y_)
    if distance < RADIUS
      player.captcha_date_time = Time.now

      if Time.now - player.last_time_on_line > 3600
        player.last_time_on_line = Time.now
        ph = PlayerOnlineHour.find(:first,:conditions => ["player_id = ? AND date = ?",player.id,Date.today])
        if ph == nil
          ph = PlayerOnlineHour.new
          ph.player_id = player.id
          ph.date = Date.today
          ph.online_hours = 0
        end
        if ph.online_hours == nil
          ph.online_hours = 0
        end
        ph.online_hours += 1
        ph.save!
      end
      player.save!
      return true
    else
      return false
    end
   
  end
  def self.parse_parameters(url,parameters)
    str = ''
    if url.nil?
      return '/castle'
    end
    parameters.each{|key,value| str += key +'='+value+'&'} unless parameters.nil?
    if url["controller"] =="quest"
      url["controller"]="castle"
      url["action"] = "index"
    end
    return  '/'+url["controller"]+'/'+(url["action"].nil? ? "index" :url["action"]+'?'+str)
  end

  #rand the don't repeat nums.
  def self.sample(n,m)
    if m.zero?
      []
    else
      s = sample(n-1,m-1)
      t = rand(n+1)
      s.concat(s.include?(t) ? [n]:[t])
    end
  end
end

你可能感兴趣的:(J#,rubygems)