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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值