Java Create picture Verification code

Source: Internet
Author: User
Tags polyline set background

Package com;

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.util.Random;

Import Javax.imageio.ImageIO;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;


public class Imgservlet extends HttpServlet {

/**
*
*/
Private static final long serialversionuid = 1L;

 private static Random random = new random ();
 private color getrandcolor (int fc, int BC) {//a given range get random color
     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);
 }

public void Goregister (HttpServletRequest request, httpservletresponse response) {
Settings page does not cache
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);

Create an image in memory
int width=100, height=40; Image size
BufferedImage image=new bufferedimage (width, height, bufferedimage.type_int_rgb);
Get the graphics context
Graphics2D G=image.creategraphics ();
G.setcolor (New Color (255, 255, 255)); Set Background color
G.fillrect (0, 0, width, height);
G.setfont (New Font ("Times New Roman", Font.Bold, 30)); Set font
Color C = Getrandcolor (160, 200);
Randomly generates 155 lines of interference so that the authentication code in the image is not easily detected by other programs
G.setcolor (c);
for (int i=0; i < 155; i++) {
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);
}
Add a noise point
float yawprate = 0.05f;//noise Rate
int area = (int) (yawprate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextint (width);
int y = random.nextint (height);
int RGB = Getrandomintcolor ();
Image.setrgb (x, y, RGB);
}
Randomly generate different fonts, font styles, and font sizes
String[] FontName = {"Microsoft Jas Black", "blackbody", "Georgia", "Verdana", "Arial", "Comic Sans MS", "Lucida Console"};
int [] FontEffect = {font.plain, font.italic, font.bold};
int [] FontSize = {28, 30, 32, 26};
font[] fonts = new Font[fontname.length*fonteffect.length*fontsize.length];
int fontsindex=0;
for (String str:fontname) {
for (int effect:fonteffect) {
for (int size:fontsize) {
Font font = new Font (str, effect, size);
Fonts[fontsindex]=font;
Fontsindex = Fontsindex +1;
}
}
}
String s= "abcdefghijknpqrstuvxyzABCDEFGHJKLNPQRSTUVXYZ23456789"; Set up an alternate verification code
String srand= "";
Draws the verification code into the image with a randomly generated color.
int length = 4; Set a default build of 4 verification codes
for (int i=0;i<length;i++) {
G.setcolor (New Color (20+random.nextint, 20+random.nextint), 20+random.nextint (110)); Generate a random color (because it's a foreground, so deep)
G.setfont (Fonts[random.nextint (fonts.length)); Random font at the top of the call
String ch=string.valueof (S.charat (Random.nextint (S.length ())));

Set Font rotation
int Zhuan = Random.nextint (20);
int Fzhuan =-random.nextint (20);
G.rotate (Math.toradians (Zhuan), 25* (i-1), 20); coordinate system clockwise rotation
G.rotate (Math.toradians (Fzhuan), 25* (i-1), 20); Coordinate system counterclockwise turn

Srand+=ch;
g.DrawString (CH, * i + 15, 30); Display the authentication code in the image with the drawstring function

G.rotate (Math.toradians ( -1*zhuan), 25* (i-1), 20);
G.rotate (Math.toradians ( -1*fzhuan), 25* (i-1), 20);
}
Draw an irregular line on the upper end of the authentication code
int visit[] = new INT[6];
for (int i = 0; i < visit.length; i++) {
Visit[i] = 1 + (int) (Math.random () * 10);
}
G.setcolor (Color.Black);
int drawhigh[] = new INT[6];
int drawwidth[] = new INT[6];
Vertex coordinates
for (int i = 0; i < 6; i++) {
Drawhigh[i] =-(int) (Math.ceil (visit[i] * 3.8));
Drawwidth[i] = 5 + i * 17;
}
G.setstroke (New Basicstroke (3.0f)); polyline thickness
G.setpaint (Color.gray);//The Color of the polyline
G.drawpolyline (DrawWidth, Drawhigh, 6); Draw a polyline
Save authentication Code to session
HttpSession session = Request.getsession (true);
String time=string.valueof (System.currenttimemillis ());
String Value=time + "_" + SRand;
Session.setattribute ("", time);
Session.setattribute ("", value);

Image effective
G.dispose ();
try {
Imageio.write (Image, "JPEG", Response.getoutputstream ()); Output image to Page
} catch (IOException e) {
E.printstacktrace ();
}
}
private static int Getrandomintcolor () {
int[] RGB = Getrandomrgb ();
int color = 0;
for (int c:rgb) {
color = Color << 8;
color = Color | C
}
return color;
}
private static int[] Getrandomrgb () {
int[] RGB = new INT[3];
Random random = new random ();
for (int i = 0; i < 3; i++) {
Rgb[i] = random.nextint (255);
}
return RGB;
}
}

Java Create picture Verification code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.