Package lizikj.bigwheel.pcsystem.util;
Import Javax.imageio.ImageIO;
Import java.awt.*;
Import Java.awt.image.BufferedImage;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.util.Date;
Import Java.util.Random;
/**
* Verification Code generator
*
* @author
*/
public class Validatecode {
The width of the picture.
private int width = 160;
The height of the picture.
private int height = 40;
Number of verification code characters
private int codecount = 5;
Number of interference lines for verification code
private int linecount = 150;
Verification Code
Private String code = NULL;
Verification Code Picture Buffer
Private BufferedImage buffimg = null;
Verification code range, minus 0 (number) and O (Pinyin) is easy to confuse (lowercase 1 and L can also be removed, uppercase No)
Private char[] Codesequence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ',
' K ', ' L ', ' M ', ' N ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ',
' X ', ' Y ', ' Z ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
/**
* default constructor, set default parameters
*/
Public Validatecode () {
This.createcode ();
}
/**
* @param width picture width
* @param height Picture high
*/
public validatecode (int width, int height) {
This.width = width;
This.height = height;
This.createcode ();
}
/**
* @param width picture width
* @param height Picture high
* @param number of Codecount characters
* @param linecount number of interference lines
*/
public validatecode (int width, int height, int codecount, int linecount) {
This.width = width;
This.height = height;
This.codecount = Codecount;
This.linecount = LineCount;
This.createcode ();
}
public void Createcode () {
int x = 0, fontheight = 0, Codey = 0;
int red = 0, green = 0, blue = 0;
x = width/(codecount + 2);//width of each character (one character left and right)
Fontheight = height of height-2;//font
Codey = height-4;
Image buffer
buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Graphics2D g = buffimg.creategraphics ();
Generate random numbers
Random random = new random ();
Fill the image with white
G.setcolor (Color.White);
G.fillrect (0, 0, width, height);
Create fonts that can be modified to other
Font font = new Font ("Fixedsys", Font.plain, Fontheight);
Font font = new Font ("Times New Roman", Font.roman_baseline, Fontheight);
G.setfont (font);
for (int i = 0; i < LineCount; i++) {
Set random start and end coordinates
int xs = random.nextint (width);//x coordinates start
int ys = random.nextint (height);//y coordinates start
int XE = xs + random.nextint (WIDTH/8);//x coordinates end
int ye = ys + random.nextint (HEIGHT/8);//y coordinates end
Generates a random color value so that the color values for each interference line of the output will be different.
Red = random.nextint (255);
Green = Random.nextint (255);
Blue = Random.nextint (255);
G.setcolor (New Color (red, green, blue));
G.drawline (XS, Ys, Xe, ye);
}
Randomcode recording of randomly generated verification codes
StringBuffer Randomcode = new StringBuffer ();
Randomly generates a Codecount character verification code.
for (int i = 0; i < Codecount; i++) {
String Strrand = string.valueof (Codesequence[random.nextint (codesequence.length)]);
Produces a random color value so that the color values for each character of the output will be different.
Red = random.nextint (255);
Green = Random.nextint (255);
Blue = Random.nextint (255);
G.setcolor (New Color (red, green, blue));
g.DrawString (Strrand, (i + 1) * x, Codey);
The resulting four random numbers are grouped together.
Randomcode.append (Strrand);
}
Save the four-digit verification code to the session.
Code = randomcode.tostring ();
}
public void Write (String path) throws IOException {
OutputStream SOS = new FileOutputStream (path);
This.write (SOS);
}
public void Write (OutputStream sos) throws IOException {
Imageio.write (buffimg, "PNG", SOS);
Sos.close ();
}
Public BufferedImage getbuffimg () {
return buffimg;
}
Public String GetCode () {
return code;
}
/**
* Test function, default build to D drive
* @param args
*/
public static void Main (string[] args) {
Validatecode Vcode = new Validatecode (160,40,5,150);
try {
String path= "d:/" +new Date (). GetTime () + ". png";
System.out.println (Vcode.getcode () + ">" +path);
Vcode.write (path);
} catch (IOException e) {
E.printstacktrace ();
}
}
}
Jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%@ taglib uri= "http:// Java.sun.com/jsp/jstl/core "prefix=" C "%>
<%@ taglib uri=" http://java.sun.com/jsp/jstl/fmt "prefix=" FMT "%
<%@ taglib uri= "http://java.sun.com/jsp/jstl/functions" prefix= "FN"%>
<c:if test = "${ PageContext.request.contextPath = = '/'},
<c:set var= "CTX" value= ""/>
</c:if>
<c:if test = "${pagecontext.request.contextpath! ="/"}",
<c:set var= "CTX" value= "${pagecontext.request.contextpath}" />
</c:if>
<script>
var ctx= ' ${ctx} ';
var type = 0;
</script>
<! DOCTYPE html>
<meta charset= "UTF-8"/>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<meta http-equiv= "Cache-control" content= "No-store"/>
<meta http-equiv= "Pragma" content= "No-cache"/>
<meta http-equiv= "Expires" content= " -10"/>
<meta http-equiv= "x-ua-compatible" content= "ie=edge,chrome=1"/>
<meta name= "viewport" content= "width=device-width, initial-scale=1.0"/>
<title> Login System </title>
<meta name= "description" content= "User login page"/>
<meta name= "viewport" content= "Width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<script type= "Text/javascript" src= "${ctx}/assets/js/jquery.min.js" ></script>
<body class= "Login-layout light-login" >
<div class= "Form-group col-lg-6" >
<label for= "id" class= "col-sm-4 Control-label" >
Verification Code:
</label>
<div class= "Col-sm-8" >
<input type= "text" id= "code" name= "code" class= "Form-control" style= "width:250px;" />
<a href= "#" onclick= "changeimg ()" > Change </a>
</div>
</div>
<script type= "Text/javascript" >
Refresh Picture
function changeimg () {
var imgsrc = $ ("#imgObj");
var src = imgsrc.attr ("src");
Imgsrc.attr ("src", Changeurl (SRC));
}
In order to make the picture inconsistent each time, that is, do not let the browser read cache, so you need to add a timestamp
function Changeurl (URL) {
var timestamp = (new Date ()). ValueOf ();
var index = Url.indexof ("?", url);
if (Index > 0) {
url = url.substring (index, Url.indexof (URL, "?"));
}
if ((Url.indexof ("&") >= 0)) {
url = url + "xtamp=" + timestamp;
} else {
url = url + "? timestamp=" + timestamp;
}
return URL;
}
</script>
</body>
Controller
/**
* Response Verification Code page
* @param request
* @param response
* @param session
* @return
* @throws Exception
*/
@RequestMapping ("/validatecode.do")
Public String Validatecode (httpservletrequest request,httpservletresponse response) throws Exception {
Format the type of response as Picture format
Response.setcontenttype ("Image/jpeg");
Suppresses image caching.
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
HttpSession session = Request.getsession (true);
Validatecode Vcode = new Validatecode (120,40,5,100);
Delete the previous
Session.removeattribute ("Randomcode");
Session.setattribute ("Randomcode", Vcode.getcode (). toLowerCase ());
Vcode.write (Response.getoutputstream ());
return null;
}
From: http://blog.csdn.net/zhulin40/article/details/51899487
Java Verification Code