Ruby RMagick 验证码生成
http://babo.javaeye.com/blog/72298
class Captcha
require 'rubygems'
require 'RMagick'
# rmagick_test.rb:4:in `require': no such file to load -- RMagick (LoadError) ,上面那个require 'rubygems' 如果不放有时会报这个错误。
include Magick
attr_reader :code, :code_image #类的2个属性
def initialize(len)
#chars = ('a'..'z').to_a-['a','e','i','o','u']
code_array=[]
codex=""
rr=0
1.upto(5) {
rr=65+rand(25)
code_array << rr
} #随机生成5个大写字母
#code_array=[rand(rr).chr,rand(rr).chr,rand(rr).chr,rand(rr).chr]
#1.upto(len) {code_array << chars[rand(chars.length)]}
granite = Magick::ImageList.new('granite:') #生成granite样式的背景
canvas = Magick::ImageList.new #定义一个画布
canvas.new_image(24*4,20, Magick::TextureFill.new(granite)) #granite放画布上
text = Magick::Draw.new #文字
#text.font_family = 'times'
text.pointsize = 20 #文字大小
cur = 10
code_array.each{|c|
c=c.to_i
c=c.chr
codex=codex+c #acs码(数字)转为字母
#rand(10) > 5 ? rot=rand(Wobble):rot= -rand(Wobble)
rand(10) > 5 ? weight = NormalWeight : weight = BoldWeight
ra=1000
while ra<100000
ra=rand(999999)
end
rn='#'+ra.to_s
text.annotate(canvas,20,20, cur,18,c){ #text对象放canvas上
self.rotation=rand(30) #旋转角度
self.font_weight = weight
self.fill = rn #text(文字)颜色
}
cur += 15
}
@code = codex #生成文字(字符串格式)
@code_image = canvas.to_blob{ #生成图片(二进制格式)
self.format="JPG"
}
end
end
img = Captcha.new(4)
File.open('img.jpg','wb+') do |f|
f << img.code_image
end
No comments :
Post a Comment