验证码源代码
easyjava吧
全部回复
仅看楼主
level 8
噢丶Right 楼主
public ByteArrayInputStream newcode(){
// 创建图像
int width = 70;
int height = 21;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Graphics2D g2d = (Graphics2D) g;
Random random = new Random();
Font mFont = new Font("华文宋体", Font.BOLD, 17);
g.setColor(getRanColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(mFont);
g.setColor(getRanColor(180, 200));
// 画随机线条
for (int i = 0; i < 300; i++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int x1 = random.nextInt(6) + 1;
int y1 = random.nextInt(12) + 1;
BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL);
Line2D line = new Line2D.Double(x, y, x + x1, y + y1);
g2d.setStroke(bs);
g2d.draw(line);
}
// 输出随机验证文字
String sRand = "";
int itmp = 0;
for (int i = 0; i < 4; i++) {
if (random.nextInt(2) == 1) {
itmp = random.nextInt(26) + 65;
} else {
itmp = random.nextInt(10) + 48;
}
char ctmp = (char) itmp;
sRand += String.valueOf(ctmp);
Color color = new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110));
g.setColor(color);
// 将文字旋转指定角度
Graphics2D g2d_word = (Graphics2D) g;
AffineTransform trans = new AffineTransform();
trans.rotate(random.nextInt(45) * 3.14 / 180, 15 * i + 10, 6);
// 缩放文字
float scaleSize = random.nextFloat() + 0.5f;
if (scaleSize < 0.8 || scaleSize > 1.1f)
scaleSize = 1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(String.valueOf(ctmp), 15 * i + 10, 14);
}
session.put("randCheckCode", sRand);
g.dispose();
ByteArrayInputStream input = null;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageOutputStream imageOut = ImageIO
.createImageOutputStream(output);
ImageIO.write(image, "JPEG", imageOut);
imageOut.close();
input = new ByteArrayInputStream(output.toByteArray());
} catch (Exception e) {
System.out.println("验证码产生出现错误:" + e.toString());
e.printStackTrace();
}
return input;
}
效果图:
要注意验证码的使用,不然发挥不了他的作用。
2013年04月28日 08点04分 1
level 11
我忘记前面的密码了[拍砖]
2013年04月28日 10点04分 2
我记得,哈哈……
2013年04月28日 10点04分
level 9
[Love][Love][Love]
2013年04月28日 10点04分 3
level 9
顶 群猪
2013年04月28日 11点04分 4
level 8
2013年04月28日 16点04分 5
level 8
什么密码我都忘记了怎么办?
2013年04月29日 06点04分 6
level 11
2013年05月01日 00点05分 7
1