Java Graphics2D绘制验证码

时间:2022-03-07 11:25:51

Java Graphics2D绘制验证码

显示界面

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function hyz(){
var img = document.getElementById("myimg");
//需要给出一个参数,避免浏览器缓存请求
img.src= "<%=request.getContextPath() %>/VerifyCodeServlet?"+new Date().getTime();
}
</script>
</head>
<body>
<form action="<%=request.getContextPath() %>/TestVerifyCodeServlet" method="post">
验证码:<input type="text" name="verifyCode"/><br>
<a href="javascript:hyz()"><img id="myimg" src="<%=request.getContextPath() %>/VerifyCodeServlet"></a><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>

请求验证码所需servlet

VerifyCodeServlet.java

//package com.jxust.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jxust.utils.VerifyCode;

@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
VerifyCode vc = new VerifyCode();
BufferedImage image = vc.getImage();//获取一次性验证码图片
// 该方法必须在getImage()方法之后来调用
System.out.println("验证码图片上的文本:"+vc.getText());//获取图片上的文本
VerifyCode.output(image, response.getOutputStream());//把图片写到指定流中

// 把文本保存到session中,为验证做准备
request.getSession().setAttribute("vCode", vc.getText());
}
}

绘制4位图片验证码

VerifyCode.java

//package com.jxust.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
private Color bgColor = new Color(255, 255, 255);
private String text ;

private Color randomColor () {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}

private Font randomFont () {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);//指定字体名称、样式和点大小,创建一个新 Font。
}
//画干扰的线条
private void drawLine (BufferedImage image) {
int num = 3;//画三条
Graphics2D g2 = (Graphics2D)image.getGraphics();
for(int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(Color.BLUE);
g2.drawLine(x1, y1, x2, y2);
}
}

private char randomChar () {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}

private BufferedImage createImage () {
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0, 0, w, h);
return image;
}

public BufferedImage getImage () {
BufferedImage image = createImage();
Graphics2D g2 = (Graphics2D)image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图片中画4个字符
for(int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 4;
g2.setFont(randomFont());
g2.setColor(randomColor());
/**
* 首字符的基线位于用户空间的 (x, h-5) 位置处
* 原点在左上角,X轴递增的方向是从左向右;Y轴是从上到下
* 在提供的坐标位于基线上最左边字符的情况下,可以从右到左呈现字形
* h-5表示y轴方向,向上偏移了5
*/

g2.drawString(s, x, h-5);
}
this.text = sb.toString();
drawLine(image);
return image;
}

public String getText () {
return text;
}

public static void output (BufferedImage image, OutputStream out)
throws IOException {
ImageIO.write(image, "JPEG", out);
}
}

测试验证码

TestVerifyCodeServlet.java

//package com.jxust.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestVerifyCodeServlet")
public class TestVerifyCodeServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println(req.getHeader("Referer"));//获取来源URL
//System.out.println(req.getRequestURL());//获取请求的URL

String verifyCode = req.getParameter("verifyCode");
String vcode = (String) req.getSession().getAttribute("vCode");
System.out.println(verifyCode.equalsIgnoreCase(vcode));//验证码是否输入正确

}
}

Java Graphics2D绘制验证码

绘制更多位的的验证码

这里通过绘制5位演示

VerifyCode2.java

//package com.jxust.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode2 {
private int w = 90;
private int h = 35;
private Random r = new Random();
// {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
private Color bgColor = new Color(255, 255, 255);
private String text ;

//随机的颜色
private Color randomColor () {
int red = r.nextInt(150);//随机数 0<=red<150
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}

private Font randomFont () {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);//指定字体名称、样式和点大小,创建一个新 Font。
}
//画干扰的线条
private void drawLine (BufferedImage image) {
int num = 3;//画三条
Graphics2D g2 = (Graphics2D)image.getGraphics();
for(int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(Color.BLUE);
g2.drawLine(x1, y1, x2, y2);
}
}

private char randomChar () {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}

private BufferedImage createImage () {
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0, 0, w, h);
return image;
}

public BufferedImage getImage () {
BufferedImage image = createImage();
Graphics2D g2 = (Graphics2D)image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图片中画5个字符
for(int i = 0; i < 5; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 5;
g2.setFont(randomFont());
g2.setColor(randomColor());
/**
* 首字符的基线位于用户空间的 (x, h-5) 位置处
* 原点在左上角,X轴递增的方向是从左向右;Y轴是从上到下
* 在提供的坐标位于基线上最左边字符的情况下,可以从右到左呈现字形
* h-5表示y轴方向,向上偏移了5
*/

g2.drawString(s, x, h-5);
}
this.text = sb.toString();
drawLine(image);
return image;
}

public String getText () {
return text;
}

public static void output (BufferedImage image, OutputStream out)
throws IOException {
ImageIO.write(image, "JPEG", out);
}
}