Java Imitation 12306 image verification code _java

Source: Internet
Author: User

Because I want to do a new project, I intend to do a simple picture verification code.

First talk about the idea bar: in the server, from a folder to find 8 pictures, and then the 8 pictures merged into a large picture, in 8 small picture randomly generated a user to verify the classification of the picture, such as puppies, beer and so on. In the front end, access to this page, the picture loaded up, the user selected in the picture on the pictures needed, when the user points to log in, according to the user's choice of all coordinates to determine whether the selected picture is actually the verification picture.

Let's put two effect graphs first:

To make the file lookup simpler, you can do this in the picture file structure:

This facilitates the generation of the user to select the key picture, and take out 8 small pictures merged into a large image.

Code: This is a selection of 8 pictures, and the recursive guarantee that the selected picture will not repeat when each picture is selected.

//select 8 pictures public static list<object> geteightimages () {//save path to every picture that is taken to ensure that the image is not heavy
  
 Complex list<string> paths = new arraylist<string> ();
 file[] finalimages = new File[8];
  
 list<object> Object = new arraylist<object> ();
  
 Save Tips string[] tips = new String[8];
  for (int i = 0; i < 8; i++) {//Get a random level two directory int dirindex = Getrandom (secondarydirnumbers);
   
  File Secondarydir = GetFiles () [Dirindex];
   
  Random folder name saved to tips tips[i] = Secondarydir.getname ();
   
  Get the two-level picture directory of the file file[] images = Secondarydir.listfiles ();
  int imageindex = Getrandom (Imagerandomindex);
   
  File image = Images[imageindex];  
   
  Image to heavy image = Dropsameimage (image, paths, tips, i);
 
  Paths.add (Image.getpath ());
   
 Finalimages[i] = image;
 } object.add (Finalimages);
 Object.add (tips);
return object; } 

In generating these 8 images, save all the file categories with an array. In this category can be used to select a random number of categories as a key category, is the user to select all the pictures. Because the arrays are ordered, you can traverse the elements in the array to get the location of each key category picture to facilitate matching when the user validates.

Gets the position, which returns the first few pictures, not the subscript, starting at 1, the collection is the tip public
 static list<object> getLocation (string[] tips) {
  List <Object> locations = new arraylist<object> ();
  
  Gets the key category
  String tip = gettip (tips);
  Locations.add (TIP);
   
  int length = Tips.length;
  for (int i = 0; i < length; i++) {
   if (tip.equals (tips[i))) {
 
    locations.add (i+1);
   }
  }
  return locations;
 }
 

After you select 8 pictures, the next step is to merge the pictures. Merging pictures can be used to bufferedimage this class of methods: Setrgb () This method if you do not understand the API document, there are detailed instructions.

 public static void Mergeimage (file[] finalimages, httpservletresponse response) throws I
   
  oexception {//Read picture BufferedImage mergeimage = new BufferedImage (A, BUFFEREDIMAGE.TYPE_INT_BGR);
    
   for (int i = 0; i < 8; i++) {File image = Finalimages[i];
   BufferedImage bufferedimage = imageio.read (image);
   int width = bufferedimage.getwidth ();
   int height = bufferedimage.getheight ();
   Read from the picture RGB int[] imagebytes = new Int[width*height];
   imagebytes = Bufferedimage.getrgb (0, 0, width, height, imagebytes, 0, width);
   if (I < 4) {Mergeimage.setrgb (i*200, 0, width, height, imagebytes, 0, width);
   else {Mergeimage.setrgb (i-4) *200, width, height, imagebytes, 0, width);
  } imageio.write (mergeimage, "JPG", Response.getoutputstream ());
 Imageio.write (mergeimage, "JPG", destimage); }
 

In the controller layer, the key classification is saved to the session, the user chooses the picture classification to make the hint and the picture verification makes the judgment. The image stream is then output to the response, and the validation picture can be generated.

Response.setcontenttype ("Image/jpeg"); 
  Response.setheader ("Pragma", "No-cache"); 
  Response.setheader ("Cache-control", "No-cache"); 
  Response.setdateheader ("Expires", 0);
  
  list<object> Object = Imageselectedhelper.geteightimages ();
  File[] Finalimages = (file[]) object.get (0);
  
  String[] tips = (string[]) object.get (1);
  The picture position of all keys, that is, the user must choose the picture
  list<object> locations = imageselectedhelper.getlocation (tips);
  
  String tip = locations.get (0). toString ();
  System.out.println (TIP);
  Session.setattribute ("Tip", tip);
  Locations.remove (0);
  
  int length = Locations.size ();
  for (int i = 0; i < length; i++) {
   System.out.println ("actual key picture position:" + locations.get (i));
  }

  Session.setattribute ("Locations", locations);
  Imagemerge.mergeimage (finalimages, response);

In the JSP, generate a small picture tag for the user's clicks. When the user point picture hits, add a child div tag to the parent Div and position him as relative, set ZIndex, and then add an IMG tag to the DIV, positioned as absolute. When the user clicks, can obtain the click event, according to the Click event obtains the click coordinates, then subtracts the parent div the coordinates, can obtain the relative coordinates.  You can set the origin of the coordinates according to your preference, where the origin of the coordinates is the lower-right corner of the 8th picture.

<div><br> <div id= "base" ><br> /identify" Style= "width:300px; height:150px "onclick=" clickimg (event) "id=" Bigpicture "><br> </div><br> <br> </div
  ><br><br>function clickimg (e) {var basediv = document.getElementById ("base");
  var topvalue = 0;
  var leftvalue = 0;
  var obj = Basediv;
   while (obj) {leftvalue + = Obj.offsetleft;
   Topvalue +=obj.offsettop;
  obj = obj.offsetparent; //solve the problem that Firefox does not get the Click event var clickevent = e?
    
  E: (window.event window.event:null);
  var clickleft = Clickevent.clientx + document.body.scrollleft-document.body.clientleft-10;
  var clicktop = Clickevent.clienty + document.body.scrolltop-document.body.clienttop-10;
  
  var divid = "Img_" + index++;
  
  var Divele = document.createelement ("div");
  Divele.setattribute ("id", divid);
  DivEle.style.position = "relative";
  DivEle.style.zIndex = index; DivEle.style.width = "20px";
  DivEle.style.height = "20px";
  
  DivEle.style.display = "inline";
  DivEle.style.top = clicktop-topvalue-150 + + "px";
  
  DivEle.style.left = clickleft-leftvalue-300 + "px";
  Divele.setattribute ("onclick", "Remove" (' + divID + ")");
  
  Basediv.appendchild (Divele);
  var Imgele = document.createelement ("img");
  IMGELE.SRC = "<%=request.getcontextpath ()%>/resources/timo.png";
  ImgEle.style.width = "20px";
  ImgEle.style.height = "20px";
  ImgEle.style.top = "0px";
  ImgEle.style.left = "0px";
  ImgEle.style.position = "absolute";
  ImgEle.style.zIndex = index;
 Divele.appendchild (Imgele);
 }

After the user chooses to log in, the server side is judged according to the user's choice coordinates

Public list<integer> Ispass (String result) {string[] xylocations = Result.split (",");
  Save user-selected coordinates on which pictures list<integer> List = new arraylist<integer> ();
  Each set of coordinates System.out.println ("user chooses the number of pictures:" +xylocations.length);
   for (String xylocation:xylocations) {string[] xy = xylocation.split ("\\|\\|");
   int x = Integer.parseint (xy[0]);
    
   int y = integer.parseint (xy[1]); 
  
    8,4 Picture Range if (x > -75 && x <= 0) {if (Y > -75 && y <= 0) {//8th List.add (8);
    else if (y >= -150 && y <=-75) {//4th List.add (4);
     ' Else if ' (X > -150 && x <=-75) {//7,3 picture interval if (y > -75 && y <= 0) {//7
  
    List.add (7);
    else if (y >= -150 && y <=-75) {//3rd List.add (3); 
     ' Else if ' (X > -225 && x <=-150) {//6,2 picture interval if (y > -75 && y <= 0) {//6
  
    List.add (6); } ELSE if (Y >= -150 && y <=-75) {//2nd List.add (2); ' Else if ' (x >= -300 && x <=-225) {//5,1 picture interval if (y > -75 && y <= 0)
  
    {//No. 5th List.add (5);
    else if (y >= -150 && y <=-75) {//1th List.add (1);
   } else {return null;
 } return list;
 

 

 }

Refresh generates a new picture, because Ajax does not support binary flow, you can use the original XMLHttpRequest object plus HTML5 blob to complete.

function Refresh () {
 var url = "<%=request.getcontextpath ()%>/identify";
 var xhr = new XMLHttpRequest ();
 Xhr.open (' Get ', url, true);
 Xhr.responsetype = "blob";
 Xhr.onload = function () {
  if (this.status = =) {
   var blob = this.response;    
   Release blob
   bigpicture.onload = function (e) {window after successful loading
    . Url.revokeobjecturl (BIGPICTURE.SRC);
   };
   bigpicture.src = window. Url.createobjecturl (BLOB);
  }
 }
 Xhr.send ();

The whole code is complete, and there are some details to deal with.

The above is the entire content of this article, I hope to help you learn.

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.