验证码

7 篇文章 0 订阅

1.

<%@ page contentType="image/jpeg" import="java.awt.*, 
java.awt.image.*,java.util.*,javax.imageio.*" %> 
<%! 
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); 

%> 
<% 
out.clear();//这句针对resin服务器,如果是tomacat可以不要这句 
response.setHeader("Pragma","No-cache"); 
response.setHeader("Cache-Control","no-cache"); 
response.setDateHeader("Expires", 0); 
int width=60, height=20; 
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
Graphics g = image.getGraphics(); 
Random random = new Random(); 
g.setColor(getRandColor(200,250)); 
g.fillRect(0, 0, width, height); 
g.setFont(new Font("Times New Roman",Font.PLAIN,18)); 
g.setColor(getRandColor(160,200)); 
for (int i=0;i<155;i++) 

int x = random.nextInt(width); 
int y = random.nextInt(height); 
int xl = random.nextInt(12); 
int yl = random.nextInt(12); 
g.drawLine(x,y,x+xl,y+yl); 

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(110),20+random.nextInt(110),20+random.nextInt(110))); 
g.drawString(rand,13*i+6,16); 

// 将认证码存入SESSION 
session.setAttribute("rand",sRand); 
g.dispose(); 
ImageIO.write(image, "JPEG", response.getOutputStream()); 
%>

2.

<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
// 在内存中创建图象


int width=60, height=20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);


// 获取图形上下文


Graphics g = image.getGraphics();


// 设定背景色


g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);


//画边框


g.setColor(Color.black);
g.drawRect(0,0,width-1,height-1);


// 随机产生的认证码(4位数字)


String rand =""+ (Math.random()*10000);
rand = rand.substring(0,rand.indexOf("."));
switch(rand.length())
{
case 1: rand = "000"+rand; break;
case 2: rand = "00"+rand; break;
case 3: rand = "0"+rand; break;
default: rand = rand.substring(0,4); break;
}


// 将认证码存入SESSION


session.setAttribute("rand",rand);


// 将认证码显示到图象中


g.setColor(Color.black);
Integer tempNumber = new Integer(rand);
String numberStr = tempNumber.toString();


g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
String Str = numberStr.substring(0,1);
g.drawString(Str,8,17);


Str = numberStr.substring(1,2);
g.drawString(Str,20,15);
Str = numberStr.substring(2,3);
g.drawString(Str,35,18);


Str = numberStr.substring(3,4);
g.drawString(Str,45,15);


// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到


Random random = new Random();
for (int i=0;i<20;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x,y,0,0);
}


// 图象生效


g.dispose();


// 输出图象到页面


ImageIO.write(image, "JPEG", response.getOutputStream());
//在页面上调用 <img src="/yourPath/checkNum.jsp" />




%>
 

3.

<%@pagecontentType=/"image/jpeg/"import=/"java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*
/"%>
  
<%!
//createbysmallnest
//email:smallnest@gmail.com
//website:www.kuaff.com
//生成随机颜色
ColorgetRandColor(Randomrandom,intfc,intbc)...{
if(fc>255)fc=255;
if(bc>255)bc=255;
intr=fc+random.nextInt(bc-fc);
intg=fc+random.nextInt(bc-fc);
intb=fc+random.nextInt(bc-fc);
returnnewColor(r,g,b);
}
%>
  
<%
//设置页面不缓存
response.setHeader(/"Pragma/",/"No-cache/");
response.setHeader(/"Cache-Control/",/"no-cache/");
response.setDateHeader(/"Expires/",0);
//设置图片的长宽
intwidth=176,height=30;
//设置备选汉字,剔除一些不雅的汉字
Stringbase=/"的一了是我不在人们有来他这上着个地到大里说就去子得也和那要下看天时过出小么起你都把好
还多没为又可家学只以主会样年想生同老中十从自面前头道它后然走很像见两用她国动进成回什边作对开而己
些现山民候经发工向事命给长水几义三声于高手知理眼志点心战二问但身方实吃做叫当住听革打呢真全才四已
所敌之最光产情路分总条白话东席次亲如被花口放儿常气五第使写军吧文运再果怎定许快明行因别飞外树物活
部门无往船望新带队先力完却站代员机更九您每风级跟笑啊孩万少直意夜比阶连车重便斗马哪化太指变社似士
者干石满日决百原拿群究各六本思解立河村八难早论吗根共让相研今其书坐接应关信觉步反处记将千找争领或
师结块跑谁草越字加脚紧爱等习阵怕月青半火法题建赶位唱海七女任件感准张团屋离色脸片科倒睛利世刚且由
送切星导晚表够整认响雪流未场该并底深刻平伟忙提确近亮轻讲农古黑告界拉名呀土清阳照办史改历转画造嘴
此治北必服雨穿内识验传业菜爬睡兴形量咱观苦体众通冲合破友度术饭公旁房极南枪读沙岁线野坚空收算至政
城劳落钱特围弟胜教热展包歌类渐强数乡呼性音答哥际旧神座章帮啦受系令跳非何牛取入岸敢掉忽种装顶急林
停息句区衣般报叶压慢叔背细/"; [Page]
//备选汉字的长度
intlength=base.length();
//创建内存图像
BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获取图形上下文
Graphicsg=image.getGraphics();
//创建随机类的实例
Randomrandom=newRandom();
//设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor(random,200,250));
g.fillRect(0,0,width,height);
//备选字体
String[]fontTypes=...{
/"宋体/",/"新宋体/",/"黑体/",/"楷体/",/"隶书/"};
intfontTypesLength=fontTypes.length;
//在图片背景上增加噪点
g.setColor(getRandColor(random,160,200));
g.setFont(newFont(/"TimesNewRoman/",Font.PLAIN,14));
for(inti=0;i<6;i++)...{
g.drawString(/"*********************************************/",0,5*(i+2));
}
//取随机产生的认证码(6个汉字)
//保存生成的汉字字符串
StringsRand=/"/";
for(inti=0;i<6;i++)...{
intstart=random.nextInt(length);
Stringrand=base.substring(start,start+1);
sRand+=rand;
//设置字体的颜色
g.setColor(getRandColor(random,10,150));
//设置字体
g.setFont(newFont(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD,18+random.nextInt(6)));


 





 


 


很多新手对图片验证码不是很了解,今天我们就来看看一个实例吧,首先,先写一个动态图片生成的Servlet类,如下:


package org.yuanliang;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class RandomCode extends HttpServlet {
private static final long serialVersionUID = 1L;


private static int WIDTH = 65;//设置图片的宽度


private static int HEIGHT = 22;//设置图片的高度


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
response.setContentType(/"image/jpeg/");
ServletOutputStream sos = response.getOutputStream();


response.setHeader(/"Pragma/", /"No-cache/");
response.setHeader(/"Cache-Control/", /"no-cache/");
response.setDateHeader(/"Expires/", 0);


BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();


char[] rands = generateCheckCode();
drawBackground(g);
drawRands(g, rands);
g.dispose();


ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, /"JPEG/", bos);
byte[] buf = bos.toByteArray();
response.setContentLength(buf.length);
sos.write(buf);
bos.close();
sos.close();
session.setAttribute(/"randomCode/", new String(rands));
}


private void drawBackground(Graphics g) {
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, WIDTH, HEIGHT);
for (int i = 0; i < 120; i++) {
int x = (int) (Math.random() * WIDTH);
int y = (int) (Math.random() * HEIGHT);
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(new Color(red, green, blue));
g.drawOval(x, y, 1, 0);[Page]
}
}


private void drawRands(Graphics g, char[] rands) {
// g.setColor(Color.BLUE);
Random random = new Random();
int red = random.nextInt(110);
int green = random.nextInt(50);
int blue = random.nextInt(50);
g.setColor(new Color(red, green, blue));
g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));
g.drawString(/"/" + rands[0], 1, 17);
g.drawString(/"/" + rands[1], 16, 15);
g.drawString(/"/" + rands[2], 31, 18);
g.drawString(/"/" + rands[3], 46, 16);
}


private char[] generateCheckCode() {
String chars = /"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/";
char[] rands = new char[4];
for (int i = 0; i < 4; i++) {
int rand = (int) (Math.random() * 36);
rands[i] = chars.charAt(rand);
}
return rands;
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}


4.

<%@ page import="java.awt.*,java.awt.image.*,java.util.*,com.sun.image.codec.jpeg.*" %> <%!//根据提供的ab产生随机的颜色变化范围Color getColor(int a,int b){        int n=b-a;        Random rd=new Random();        int cr=a+rd.nextInt(n);        int cg=a+rd.nextInt(n);        int cb=a+rd.nextInt(n);                 return new Color(cr,cg,cb);        }%> <%   //下边三行取消客户端游览器缓存验证码的功能response.setHeader("Pragma","No-cache");response.setHeader("Cache-Control","no-cache");response.setDateHeader("Expires", 0); int width=60, height=20;//在内存中生成一个图像BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getColor(200,250));g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman",Font.BOLD,18)); g.setColor(getColor(160,200));for (int i=0;i<160;i++){int x = random.nextInt(width);int y = random.nextInt(height);        int xl = random.nextInt(12);        int yl = random.nextInt(12);g.drawLine(x,y,x+xl,y+yl);} String number=String.valueOf(1000+random.nextInt(8999));String name=request.getParameter("name");session.setAttribute(name,number); g.setColor(getColor(20,130));int x=(int)(width*0.2);int y=(int)(height*0.8);g.drawString(number,x,y);g.dispose(); JPEGImageEncoder   encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());          encoder.encode(image);       out.close();      %> 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值