用java写的比较好看的验证码程序

package com.apectra.pub;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Vimage extends HttpServlet {
public void destroy() {
super.destroy();
}
/*
* service
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//首先设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires",0);
//定义图片的宽度和高度
int width = 90;
int height = 30;
//创建一个图片对象
BufferedImage image= new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//得到图像的环境对象
Graphics g = image.createGraphics();
//用随机颜色填充图像背景
Random random = new Random();
g.setColor(getColor(180,250));
g.fillRect(0, 0, width, height);
for(int i=0; i< 5; i++)
{
g.setColor(getColor(50,100));
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 4, 4);
}

g.setFont(new Font("",Font.PLAIN,28));
//生成随机字符串
String sRand = "";
for(int i = 0; i< 4; i++)
{
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
//生成随机颜色
g.setColor(new Color(20+random.nextInt(80),20+random.nextInt(100),20+random.nextInt(90)));
g.drawString(sRand,15,25);
//生成干扰向
for(int j=0;j<12;j++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(9);
int y1 = random.nextInt(9);
g.drawLine(x, y, x+x1, y+y1);
}
}
request.getSession().setAttribute("randCode",sRand);
//使画像生成
g.dispose();
//输出图形到页面
ImageIO.write(image, "jpg", response.getOutputStream());
}

/**
* 产生一个随机的颜色
* @return
*/
public Color getColor(int fc,int bc)
{
Random random = new Random();
if(fc > 255)
{
fc = 255;
}
if(bc > 255)
{
bc = 255;
}

int red = fc + random.nextInt(bc - fc);
int green = fc + random.nextInt(bc - fc);
int blue = fc + random.nextInt(bc - fc);

return new Color(red,green,blue);
}
public void init() throws ServletException {

}


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值