Java implementation of a verification code picture function

Source: Internet
Author: User

The ability to generate a picture of a CAPTCHA using Java

    First of all, this code is not my writing, but I copy, because I wrote out the function is there, but particularly ugly, so it does not look,

First of all, the principle

Using Java to generate a picture this is a Java GUI programming knowledge, using him to dynamically generate a picture of the stream, and then send to the client is ready, the code is as follows

Back-end:,

      

Package Com.servlet;import Java.awt.color;import java.awt.font;import java.awt.graphics;import Java.awt.Graphics2D; Import Java.awt.image.bufferedimage;import Java.io.bufferedreader;import Java.io.filereader;import Java.io.ioexception;import Java.util.arraylist;import Java.util.list;import Java.util.random;import Javax.imageio.imageio;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import  Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * Verification Code Generator * * * */public class Imageservlet extends HttpServlet {//Collection save all idioms private list<string> words = new arraylist<string> (); @ overridepublic void Init () throws Servletexception {//initialization phase, read new_words.txt//Web project read file, must use absolute disk path, string path = Getser Vletcontext (). Getrealpath ("/web-inf/new_words.txt"); try {BufferedReader reader = new BufferedReader (New FileReader ( path)); String Line;while (line = Reader.readline ())! = null) {Words.add (line);} Reader.close ();} catch (ioexception e) {e.printstacktrace ();}} public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Disable cache//Response.setheader ("Cache-control", "No-cache");//Response.setheader ("Pragma", "No-cache");// Response.setdateheader ("Expires",-1); int width = 120;int height = 30;//Step One draws an in-memory picture bufferedimage bufferedimage = new Bu Fferedimage (width, height,bufferedimage.type_int_rgb);//Step two picture draw background color---by drawing object graphics graphics = Bufferedimage.getgraphics ();//You must specify a color Graphics.setcolor (Getrandcolor (200, 250) before drawing objects---brush//Draw any graphics. Graphics.fillrect (0, 0, width, height);//Step three draw the Border Graphics.setcolor (Color.White); graphics.drawrect (0, 0, width-1, HEIGHT-1)///Step 44 random number graphics2d graphics2d = (graphics2d) graphics;//Set Output font graphics2d.setfont (new font ("Arial", Font.bo LD, 18)); Random random = new random ();//generates a stochastic number int index = Random.nextint (Words.size ()); String Word = words.get (index);//Get idiom//define x coordinate int x = 10;for (int i = 0; i < word.length (); i++) {//Random color Graphics2d.setcolor (new color (+ random.nextint), + random.nextint (+), + random.nextint (110)),//spin Ext. -30---30 degrees int jiaodu = Random.nextint (60)-30;//conversion radians Double theta = Jiaodu * math.pi/180;//get alphanumeric char c = Word.char at (i);//output C to picture Graphics2d.rotate (Theta, X, D); Graphics2d.drawstring (String.valueof (c), x); Graphics2d.rotate (- Theta, x + +); x + = 30;} Save the Captcha content Sessionrequest.getsession (). SetAttribute ("checkcode_session", word);//step five draw the interference line Graphics.setcolor ( Getrandcolor, int x1;int x2;int y1;int y2;for (int i = 0; i <; i++) {x1 = random.nextint (width); x2 = Rando Y1 = random.nextint (height), y2 = Random.nextint (m.nextint); Graphics.drawline (x1, y1, x1 + x2, x2 + y2);} Output the above image to the browser imageiographics.dispose ();//Release the resource//write the picture to Response.getoutputstream () in Imageio.write (BufferedImage, " JPG ", response.getoutputstream ());} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (Request, Response);} /** * Take a range of Color * * @param FC * int Range parameter 1 * @param BC * INT Range Parameter 2 * @return Color */private Colo R Getrandcolor (int FC, int BC) {//take its random colors random random = new random (), 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);}}

Front desk Use

    

1<! DOCTYPE html>234<title>insert title here</title>5<script type= "Text/javascript" >6Window.onload =function () {7         8     }9     Ten function changeimg (obj) { OneObj.src= "/testuploaddownload/imageservlet?time=" +NewDate (). GetTime (); A     } -  -      the</script> -  - -<body> +<form action= "" method= "POST" > -User name: <input type= "text" name= "username" ><br/> +Password <input type= "password" name= "password" ><br/> ACaptcha <input type= "text" name= "username" ><br/> at<input type= "Submit" value= "Submission" ><br/> -</form> -</body> -

Effect

  

This verification code is the emergence of a Chinese idiom

Java implementation of a verification code picture function

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.