1. [代码]初始粗糙代码

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.*;
/**
* 验证码图片生成Servlet类,直接调用该Servlet即可使用
* 取值的时候调用session.getAttribute("code")得到生成的值
* @author <a href="mailto:weijunqiang2010@gmail.com">Ajunboys</a>
*
*/
@WebServlet("/safecode")
public class SafeCodeImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
Random random = new Random(); if (fc > 255)
fc = 255; if (fc < 0)
fc = 0; if (bc > 255)
bc = 255; if (bc < 0)
bc = 0; 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);
} @Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 设置输出
response.setContentType("image/jpeg"); int width = 80;
int height = 30; // 产生随机数
Random r = new Random();
// 把随机数绘制成图像 BufferedImage imgbuf = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);// 产生缓冲图像,80宽30高 Graphics2D g = imgbuf.createGraphics();// 取得缓冲的绘制环境 // 开始绘制
g.setColor(getRandColor(200, 250));// 设定背景色
g.fillRect(0, 0, width, height);// 矩形图 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) {
int x = r.nextInt(width);
int y = r.nextInt(height);
int xl = r.nextInt(12);
int yl = r.nextInt(12); g.drawLine(x, y, x + xl, y + yl);
} g.setColor(getRandColor(120, 240)); // 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
for (int i = 0; i < 100; i++) {
int x = r.nextInt(width);
int y = r.nextInt(height); g.drawOval(x, y, 0, 0);
} g.setFont(new Font("Times New Roman", Font.PLAIN, 26)); String scode = ""; for (int i = 0; i < 4; i++) {
// String rand = String.valueOf(r.nextInt(10));
String rand = randomCode(); scode += rand; g.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110),
20 + r.nextInt(110))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand+" ", (0==i) ? 12 : (12 * (i+1)+5), 23);
} request.getSession().setAttribute("safecode", scode); // 输出图像
ServletOutputStream out = response.getOutputStream();// 得到HTTP的流 // JPEGCodec.createJPEGEncoder(out);转码
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);// 产生JPEG的图像加码器 encoder.encode(imgbuf);
out.flush();
} private static String randomCode(){
char[] dictionary = {
'2','3','4','5','6','7','8','9'
,'a','b','c','d','e','f','g','h','i','j'
,'k','m','n','p','q','r','s','t'
,'u','v','w','x','y','z'
,'A','B','C','D','E','F','G','H','J'
,'K','L','M','N','P','Q','R','S','T'
,'U','V','W','X','Y','Z'
/*'1','l','0','O','o','#','@','$','%','&','(',')','|','/','*'//暂时不用特殊字符(包括:数字1,0;字母:l,o,O)
,'^','!','~','\\'*/
};
StringBuffer code = new StringBuffer(); Random r = new Random(); code.append(dictionary[r.nextInt(dictionary.length)]); return code.toString();
} }

2. [代码]优化后的全代码

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder; /**
* 验证码图片生成Servlet类,直接调用该Servlet即可使用
* 取值的时候调用session.getAttribute("code")得到生成的值
* @author <a href="mailto:weijunqiang2010@gmail.com">Ajunboys</a>
*
*/
@WebServlet("/safecode")
public class SafeCodeImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L; static final char[] dictionary = {
'2','3','4','5','6','7','8','9'
,'a','b','c','d','e','f','g','h','i','j'
,'k','m','n','p','q','r','s','t'
,'u','v','w','x','y','z'
,'A','B','C','D','E','F','G','H','J'
,'K','L','M','N','P','Q','R','S','T'
,'U','V','W','X','Y','Z'
/*'1','l','0','O','o','#','@','$','%','&','(',')','|','/','*'//暂时不用特殊字符(包括:数字1,0;字母:l,o,O)
,'^','!','~','\\'*/
};
static Random random = new Random(); /**
* 产生n[4,4+]个随机数
* @param n
* @return
*/
static String getRandomString(int n){
StringBuffer buffer = new StringBuffer();
if (n < 4) {
n = 4;
}
for (int i = 0; i < n; i++) {
buffer.append(dictionary[random.nextInt(dictionary.length)]);
}
return buffer.toString();
} /**
* 随机颜色
* @return
*/
static Color getRandomColor(){
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
} /**
* 颜色反色
* @param c
* @return
*/
static Color getReverseColor(Color c){
return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg"); String randomString = getRandomString(6); request.getSession(true).setAttribute("code", randomString); int width = 100; //验证码图片宽度
int height = 30; //验证码图片高度 Color color = getRandomColor(); Color reverse = getReverseColor(color); //创建一个彩图
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //绘图对象
Graphics2D g = bi.createGraphics(); g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
g.setColor(color);
g.fillRect(0, 0, width, height);
g.setColor(reverse);
g.drawString(randomString, 18, 20); //绘制最多100个噪音点
for (int i = 0, n = random.nextInt(100); i < n; i++) {
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
} ServletOutputStream out = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(bi); out.flush(); out.close();
} }

最新文章

  1. Django基础,Day7 - 添加静态文件 static files
  2. textarea{resize:none}
  3. 【MySQL学习笔记】MySQL权限表
  4. GPIO相关知识
  5. UVA 12657 Boxes in a Line 双向链表
  6. textview自适应高度的计算方法
  7. 搭建PHP环境LAMP(Linux+Apache+MySQL+PHP)
  8. OC-字典
  9. [itint5]判断是否为二叉搜索树
  10. How to: Implement a Windows Communication Foundation Service Contract
  11. java 容器类大集结
  12. Java Collection 集合类大小调整带来的性能消耗
  13. OCP读书笔记(22) - 题库(ExamB)
  14. 支持持久化的内存数据库-----Redis
  15. InstallShield -6109
  16. 网站开发进阶(十一)如何将一个jsp页面嵌套在另一个页面中
  17. Hive入门学习--HIve简介
  18. Fiddler抓包【5】_Fiddler过滤
  19. 运输计划NOIP2015Day2T3
  20. appium+java报错之nodejs报错

热门文章

  1. 透过Extjs学习JavaScript---闭包篇
  2. List的数据结构
  3. GitHub for Mac
  4. [置顶] JSP中使用taglib出错终极解决办法
  5. poj1190 生日蛋糕 dfs
  6. kindle paperwhite 使用说明
  7. 经典C面试题
  8. [Reduc] React Counter Example
  9. OleDb 读取 excel
  10. 3_Linux_文件搜索指令