【网络棋牌源码下载】【飞车改车源码】【javaqq抢红包源码】java验证码源码_java验证码代码
1.验证码部分的验证a验java代码怎么写
验证码部分的java代码怎么写
package com.bbs.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet..sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Image extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width = , height = ;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(, ));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, ));
// 随机产生条干扰线,使图象中的码源码网络棋牌源码下载认证码不易被其它程序探测到
g.setColor(getRandColor(, ));
for (int i = 0; i < ; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt();
int yl = random.nextInt();
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
String sRand =setRandValue(request);
if(sRand!=null)
for (int i = 0; i < sRand.length(); i++) {
g.setColor(new Color( + random.nextInt(), + random
.nextInt(), + random.nextInt()));
// 调用函数出来的颜色相同,可能是证码飞车改车源码因为种子太接近,所以只能直接生成
g.drawString(sRand.charAt(i) + "",代码javaqq抢红包源码 * i + 6, );
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
// 图象生效
g.dispose();
// 输出图象到页面
// ImageIO.write(image, "JPG", response.getOutputStream());
out.flush();
out.close();
}
Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色
Random random = new Random();
if (fc > )
fc = ;
if (bc > )
bc = ;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
//-对应0-9;-对应A-Z;-对应a-z;
String setRandValue(HttpServletRequest request) {
Random random = new Random();
String sRand = "";
//这里是生成验证码的位数
for (int i = 0; i < 4; i++) {
char c = 0;
int k = random.nextInt(3);
switch (k) {
case 0:
c = (char) (random.nextInt() + );
break;
case 1:
c = (char) (random.nextInt() + );
break;
case 2:
c = (char) (random.nextInt() + );
}
sRand += c;
}
request.getSession().setAttribute("rands", sRand);
return sRand;
}
}