java生成图片验证码实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java生成图片验证码实现相关的知识,希望对你有一定的参考价值。
两种图片样式分别是用Graphics类和Graphics2D
类实现(Graphics2D扩展了Graphics类),可以参考资料,画出自己想要的图片
Graphics2D 参考api地址:http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html
Graphics 参考api地址:http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html
代码实现一 :
java部分:
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.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; public class ImageCreate2 extends HttpServlet { private static final long serialVersionUID = 1L; private int imageWidth = 70; private int imageHeight = 20; private int codeNumber = 4; private int backGround = 30; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { createCode(request, response); } /** * @param request * @param response * @throws IOException */ private void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_BGR); Graphics2D g = bufferedImage.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, imageWidth - 1, imageHeight - 1); //g.setStroke(new BasicStroke(3.0f));//干扰线 Random random = new Random(); for (int i = 0; i < backGround; i++) { int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); g.setColor(new Color(red, green, blue)); int start_X = random.nextInt(imageWidth); int start_Y = random.nextInt(imageHeight); if (random.nextInt(5) % 3 == 0) { int r = random.nextInt(10); int startAngle = random.nextInt(360); int arcAngle = random.nextInt(360); g.drawArc(start_X, start_Y, r, r, startAngle, arcAngle); } else { int change_X = random.nextInt() % 6; int change_Y = random.nextInt() % 6; g.drawLine(start_X, start_Y, start_X + change_X, start_Y + change_Y); } } StringBuilder ValidateCode = new StringBuilder(); g.setFont(new Font("Blackoak Std", Font.BOLD, imageHeight-2)); g.setFont(new Font("Tahoma", Font.BOLD, imageHeight - 3)); for (int i = 0; i < codeNumber; i++) { int red = random.nextInt(100) + 50; int green = random.nextInt(100) + 50; int blue = random.nextInt(100) + 50; g.setColor(new Color(red, green, blue)); String code = null; int type = random.nextInt(3); if (type == 1) { code = String.valueOf((char) (random.nextInt(26) + 65)); } else if (type == 2) { code = String.valueOf((char) (random.nextInt(26) + 97)); } else { code = String.valueOf(random.nextInt(10)); } ValidateCode.append(code); g.drawString(code, imageWidth / codeNumber * i + 4, 16); } System.out.println("vcode="+ValidateCode.toString());
//存于session中,以待验证 request.getSession().setAttribute("validateCode", ValidateCode.toString()); ServletOutputStream sos = response.getOutputStream(); ImageIO.write(bufferedImage, "jpeg", sos); bufferedImage = null; sos.close(); random = null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);
jsp页面部分:
<div class="form-group"> <div class="col-sm-10" style="width:40%;"> <input style="height: 40px" type="text" class="form-control" id="tpyzm" flag="0" placeholder="请输入验证码"> </div> <div class="col-sm-2 control-label" style="padding:7px; text-align: center;width: 80px;background: #fefefe;border:solid 1px #c9c9c9 "> <img src="<%=request.getContextPath()%>/ImageCreate2.do" id="codes2" onclick="reloadImg2(‘<%=request.getContextPath()%>‘)" class="vcodeCss"></img> </div> <div style="height: 40px;padding-top: 10px"> <span style="color: #333333;font-size: 16px;margin-left: 10px"> 看不清?</span> <a style="font-size: 16px;color: #0089d2" onclick="reloadImg2(‘<%=request.getContextPath()%>‘)">换一张</a> </div> <div class="regist_til col-sm-2"> <span class="" aria-hidden="true" id="tpyzmSpan" ></span> </div> </div>
<script>
//图片验证码
function reloadImg2(url) {
document.getElementById("codes2").src = url+"/ImageCreate2.do?" + "radom="
+ Math.random();
$("#vcode2").focus();
}
</script>
代码实现二 :
java部分:
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.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ImageCreate extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { create(request, response); } private void create(HttpServletRequest request, HttpServletResponse response) throws IOException { int []a = null; // 大小 int width = 60; int height = 30; // 声明一个图片类型rgb BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); // 获取画笔 Graphics g = bi.getGraphics(); // 背景色 g.setColor(Color.WHITE); // 画 g.fillRect(0, 0, width, height); // 字体 g.setFont(new Font("黑体", Font.BOLD, 18)); // 写一个字符到bi Random r = new Random(); for (int i = 0; i < 4; i++) { // 生成随机数 int code = r.nextInt(10);// 0---9之间 // 画笔随机色 g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256))); // 写出字符 g.drawString("" + code, i * 15, 10 + r.nextInt(20)); } //干扰线 for(int i=0;i<12;i++){ g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256))); //画线 g.drawLine(r.nextInt(60), r.nextInt(30), r.nextInt(60), r.nextInt(30)); } g.dispose();//图片生成 //ImageIO.write(bi,"JPEG", new FileOutputStream("e:/a.jpg"));//设置路径为e:盘下的a.jpg ServletOutputStream sos = response.getOutputStream(); ImageIO.write(bi, "jpeg", sos); sos.close(); bi = null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
jsp页面部分:同上,只需改下url则可;
以上是关于java生成图片验证码实现的主要内容,如果未能解决你的问题,请参考以下文章