/*1.定义图片类*/
package servlet;
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.http.HttpServletResponse;
public class RandImgCreater {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
//图片上的字符
private static final String CODE_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
private HttpServletResponse response = null;
private static final int HEIGHT = 20;//图片高度
private static final int FONT_NUM = 4;//图片上字符个数
private int width = 0;//图片宽度
private int iNum = 0;//图片上字符个数
private String codeList = "";//图片上的字符
private boolean drawBgFlag = false;
private int rBg = 0;//背景色
private int gBg = 0;//背景色
private int bBg = 0;//背景色
/**
*
* @param response
*/
public RandImgCreater(HttpServletResponse response) {
this.response = response;
this.width = 13 * FONT_NUM + 12;
this.iNum = FONT_NUM;
this.codeList = CODE_LIST;
}
/**
*
* @param response
* @param iNum 图片上字符个数
* @param codeList 图片上的字符
*/
public RandImgCreater(HttpServletResponse response, int iNum, String codeList) {
this.response = response;
this.width = 13 * iNum + 12;
this.iNum = iNum;
this.codeList = codeList;
}
/**
* 生成图片
* @return 图片上的字符
*/
public String createRandImage() {
BufferedImage image = new BufferedImage(width, HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
//自定义图片背景颜色
if (drawBgFlag) {
g.setColor(new Color(rBg, gBg, bBg));
g.fillRect(0, 0, width, HEIGHT);
} else {//随机生成图片背景颜色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, HEIGHT);
for (int i = 0; i < 155; i++) {
g.setColor(getRandColor(140, 200));
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);
}
}
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
String sRand = "";//随机生成的字符串
for (int i = 0; i < iNum; i++) {
int rand = random.nextInt(codeList.length());
String strRand = codeList.substring(rand, rand + 1);
sRand += strRand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(strRand, 13 * i + 6, 16);
}
g.dispose();
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return sRand;
}
/**
* 设置背景颜色
* @param r
* @param g
* @param b
*/
public void setBgColor(int r, int g, int b) {
drawBgFlag = true;
this.rBg = r;
this.gBg = g;
this.bBg = b;
}
/**
* 随机生成颜色
* @param fc
* @param bc
* @return
*/
private 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);
}
}
/*2.配置在servlet中*/
package servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ImageServlet1
*/
public class ImageServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImageServlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("===========request==============");
HttpSession session=request.getSession(true);
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
RandImgCreater rc = new RandImgCreater(response);
// RandImgCreater rc = new RandImgCreater(response,8,"abcdef");
// rc.setBgColor(100,100,100);
String rand = rc.createRandImage();
session.setAttribute("rand", rand);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
/*3.jsp界面应用*/
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript" src="/js/jquery.js"></script>
</head>
<body>
<%
String code=request.getParameter("code");
if(session.getAttribute("rand")!=null&&((String)session.getAttribute("rand")).equalsIgnoreCase(code)){
out.println("<span style=\"color:#FF0000\"> 验证成功!</span>");
}
%>
<form name="frm" method="post" action="./myrandTest.jsp">
Hello Image Test<br/>
checkCode:<img id="img_check" src="http://localhost:8080/mailreader/ImageServlet1" >
<a href="#" οnclick="getpic();">看不清换张图片</a>
<br />
please input the checkCode:<input type="text" name="code" value=""><br />
<input type="submit" name="btn1" value="check"></form>
</body>
<script type="text/javascript">
function getpic(){
var requesturl="http://localhost:8080/mailreader/ImageServlet1?d="+new Date();
document.getElementById("img_check").src=requesturl;
//alert(document.getElementById("img_check").src);
return false;
}
</script>
</html>