今天用jruby 改写了java版的验证码,感觉jruby的确十分强(个人观点:)),可以结合java的健壮性和ruby的便捷性,以下是代码:
环境:
jruby 1.1.3 (ruby 1.8.6 patchlevel 114) (2008-07-20 rev 7243) [x86-java]
Rails 2.1.0
netbeans IDE 6.1
java version "1.5.0_06"
代码:
帮助模块:
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#
# To change this template, choose Tools | Templates
# and open the template in the editor.
require "java"
def get_font(max_font_size,min_font_size)
myRandom = java.util.Random.new
fonts =java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment.getAllFonts
numero = myRandom.nextInt(fonts.length)
font = fonts[java.lang.Math.abs(numero)]
plus = 0
if ( max_font_size - min_font_size != 0)
plus = java.lang.Math.abs(myRandom.nextInt(max_font_size - min_font_size))
end
styled =java.awt.Font.new(font.toString, java.awt.Font::PLAIN, min_font_size + plus)
at =java.awt.geom.AffineTransform.new
angle = myRandom.nextFloat / 3
at.rotate(myRandom.nextBoolean ? angle : -angle)
trans = styled.deriveFont(at)
rx = myRandom.nextDouble % 0.3
ry = myRandom.nextDouble % 0.3
at1 = java.awt.geom.AffineTransform.getShearInstance(rx, ry)
return trans.deriveFont(at1)
end
def image_data (code,w,h)
rand = java.util.Random.new
image = java.awt.image.BufferedImage.new(w, h,java.awt.image.BufferedImage::TYPE_3BYTE_BGR)
g = image.getGraphics
g.setColor(java.awt.Color::LIGHT_GRAY)
g.fillRect(0, 0, w, h)
g.setColor(java.awt.Color::YELLOW)
#画点
0.upto(49) {|i|
x = rand.nextInt(w)
y = rand.nextInt(h)
g.drawLine(x,y,x,y)
}
#画线
0.upto(4) {|i|
x1 = rand.nextInt(w)
y1 = rand.nextInt(h)
x2 = rand.nextInt(w)
y2 = rand.nextInt(h)
g.drawLine(x1,y1,x2,y2)
}
temp_int = w - h * code.length
x = rand.nextInt(temp_int)
#画字符
0.upto(code.length-1) {|i|
y = rand.nextInt(h/4)
s = code[i..i ]
font = get_font(h,h-5)
g.setFont(font)
g.drawString(s, x,font.getSize-y )
x = x + font.getSize
}
output = java.io.ByteArrayOutputStream.new
encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(output)
param = encoder.getDefaultJPEGEncodeParam(image)
param.setQuality(0.8,false)
encoder.encode(image,param)
return output.toByteArray
end
#w = 200
#h = 40
#str = "asdf"
#file=java.io.FileOutputStream.new("c:/tmp/test.jpg")
#file.write(image_data(str, w, h))
#file.close()
end
控制器:
class LoginController < ApplicationController
helper "application"
include ApplicationHelper
def get_vailidate_img
w=150
h=34
chars = ('a'..'z').to_a
code = ""
1.upto(4) {code << chars[rand(chars.length)]}
image = image_data(code,w,h)
#把验证码字符放入session
session[:code] = code
send_data String.from_java_bytes(image), :type => 'image/jpeg', :disposition => 'inline'
end
end
页面验证码图片html代码:<img src="/login/get_vailidate_img">