jsp生成验证码

<%@page import="java.awt.Font"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.awt.Graphics"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="java.util.Random"%>
<%@page import="java.awt.Color"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
//设置页面不缓存  
response.setHeader("Pragma","no-cache");  
response.setHeader("Cache-Control","no-catch");  
response.setDateHeader("Expires",0);  


//在内存中创建图象  
int width = 90;  
int height = 30;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


Graphics pic = image.getGraphics();
Random r = new Random();
// 设置 图像的背景颜色
pic.setColor(getRandColor(r.nextInt(50),r.nextInt(100)+50));
pic.fillRect(0, 0, width, height);


// 绘制 干扰线
pic.setColor(Color.gray);


for(int i = 0; i < 30; i++){ 

    int x = r.nextInt(width);  
    int y = r.nextInt(height);  
    int xl = r.nextInt(width);  
    int yl = r.nextInt(height);  
    
    pic.drawLine(x, y, xl, yl);
}  




int n1 = r.nextInt(10);
int n2 = r.nextInt(10);
int n3 = r.nextInt(10);
int n4 = r.nextInt(10);


String result = n1 + n2 + n3 + n4 + "";


//生成的结果放在 什么地方  客户 可以随时用来对比
session.setAttribute("code", result);




System.out.println(result);


pic.setColor(Color.black);


pic.setFont(new Font("Arial",Font.BOLD, 16));


pic.drawString(n1+"", r.nextInt(15)+4, r.nextInt(16)+12);


pic.setColor(Color.black);


pic.setFont(new Font("Arial",Font.BOLD, 16));


pic.drawString(n2+"", r.nextInt(15)+22, r.nextInt(16)+12);


pic.setColor(Color.black);


 pic.setFont(new Font("Arial",Font.BOLD, 16));


pic.drawString(n2+"", r.nextInt(15)+40, r.nextInt(16)+12);


pic.setColor(Color.black);


pic.setFont(new Font("Arial",Font.BOLD, 16));


pic.drawString(n3+"", r.nextInt(15)+55, r.nextInt(16)+12);




//图像生效  
pic.dispose();  
//输出图像到页面  
ImageIO.write(image,"JPEG",response.getOutputStream());  
out.clear();  
out = pageContext.pushBody();  


%>


<%!  
    Color getRandColor(int fc,int bc){  
        Random random = new Random();  
        if(fc > 255){  
            fc = 255;  
        }  
        if(bc < 255){  
            bc = 255;  
        }  
        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);  
    }  
%>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值