rails實現驗證碼
網上其實有一大堆這樣的資料了,我再寫也沒多大價值,談下幾個注意點吧。1.在windows上安裝Rmagic,如果你是通過gem安裝的,
require 'Rmagic'
要修改為:
require 'rubygems'
require 'Rmagick'
才能正確引入。require 'Rmagick'
2.網上那個例子,畫布是使用Rmagic內置的圖像格式,Rmagic內置的圖像格式還有:
gradient*
梯度,比如gradient:red-bluegranite
花崗石,比如: "granite:"
.
logo
logo型的圖像. 如: "logo:"
,後麵會多顯示一個五角星^_^
netscape
非常漂亮的彩條。如: "netscape:"
null*
空白 使用方式: "null:"
玫瑰 使用方式 : "rose:"
xc*
設置一個背景色,比如"xc:green"
一個修改的例子,在rails的models下存為noisy_image.rb,在Controller就可以這樣調用NoisyImage.new(6) :
require 'rubygems'
require 'Rmagick'
class NoisyImage
include Magick
attr_reader :code, :code_image
Jiggle = 15
Wobble = 15
def initialize(len)
chars = ('a'..'z').to_a - ['a','e','i','o','u']
code_array=[]
1.upto(len) {code_array << chars[rand(chars.length)]}
granite = Magick::ImageList.new('xc:#EDF7E7')
canvas = Magick::ImageList.new
canvas.new_image(32*len, 50, Magick::TextureFill.new(granite))
text = Magick::Draw.new
text.font_family = 'times'
text.pointsize = 40
cur = 10
code_array.each{|c|
rand(10) > 5 ? rot=rand(Wobble):rot= -rand(Wobble)
rand(10) > 5 ? weight = NormalWeight : weight = BoldWeight
text.annotate(canvas,0,0,cur,30+rand(Jiggle),c){
self.rotation=rot
self.font_weight = weight
self.fill = 'green'
}
cur += 30
}
@code = code_array.to_s
@code_image = canvas.to_blob{
self.format="JPG"
}
end
end
require 'Rmagick'
class NoisyImage
include Magick
attr_reader :code, :code_image
Jiggle = 15
Wobble = 15
def initialize(len)
chars = ('a'..'z').to_a - ['a','e','i','o','u']
code_array=[]
1.upto(len) {code_array << chars[rand(chars.length)]}
granite = Magick::ImageList.new('xc:#EDF7E7')
canvas = Magick::ImageList.new
canvas.new_image(32*len, 50, Magick::TextureFill.new(granite))
text = Magick::Draw.new
text.font_family = 'times'
text.pointsize = 40
cur = 10
code_array.each{|c|
rand(10) > 5 ? rot=rand(Wobble):rot= -rand(Wobble)
rand(10) > 5 ? weight = NormalWeight : weight = BoldWeight
text.annotate(canvas,0,0,cur,30+rand(Jiggle),c){
self.rotation=rot
self.font_weight = weight
self.fill = 'green'
}
cur += 30
}
@code = code_array.to_s
@code_image = canvas.to_blob{
self.format="JPG"
}
end
end
3.與rails應用的結合,和一般的驗證碼原理一樣,將產生的隨機數存儲在session或者request範圍內,提交的時候進行比較驗證即可。比如產生圖片的時候將隨機字母存儲在session[:code]中:
session[:noisy_image] = NoisyImage.new(6)
session[:code] = session[:noisy_image].code
驗證的時候,比較提交的type_code與session[:code]即可,為了安全性考慮,最好還是不考慮使用客戶端驗證。
unless session[:code]==params[:type_code]
flash[:notice]='驗證碼填寫錯誤,請重新注冊,謝謝!'
return redirect_to :action=>:new
end
flash[:notice]='驗證碼填寫錯誤,請重新注冊,謝謝!'
return redirect_to :action=>:new
end
在頁麵顯示圖片,類似servlet一樣直接調用Controller的action:
def code_image
image = session[:noisy_image].code_image
send_data image, :type => 'image/jpeg', :disposition => 'inline'
end
<img height='30' src="/test/code_image">
image = session[:noisy_image].code_image
send_data image, :type => 'image/jpeg', :disposition => 'inline'
end
<img height='30' src="/test/code_image">
文章轉自莊周夢蝶 ,原文發布時間5.17
最後更新:2017-05-17 13:35:08