JAVA生成图片验证码

来源:互联网 发布:2009网络流行歌曲大全 编辑:程序博客网 时间:2024/06/17 22:43

原文地址:http://blog.csdn.net/ruixue0117/article/details/22829557 本屌稍作修改!再加一个基础功能的方法

一:基础功能方法

Img.java
[java] view plaincopy
  1. import java.awt.Color;  
  2. import java.awt.Font;  
  3. import java.awt.Graphics;  
  4. import java.awt.image.BufferedImage;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7. import java.io.OutputStream;  
  8. import javax.imageio.ImageIO;  
  9.   
  10. public class Img {  
  11.     public static void outputCodeImg (int width,int height,String code,OutputStream os ) throws FileNotFoundException, IOException {  
  12.         BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR_PRE);  
  13.         //获取画笔  
  14.         Graphics gra = bi.getGraphics();  
  15.         //设置背景颜色  
  16.         gra.setColor(Color.BLACK);  
  17.         //填充背景颜色  
  18.         gra.fillRect(00, width, height);  
  19.         //第二次 设置字体颜色  
  20.         gra.setColor(Color.red);  
  21.         //设置字体样式和大小  
  22.         gra.setFont(new Font(null, Font.HANGING_BASELINE,20));  
  23.         //描绘  
  24.         gra.drawString(code.toString(), 5, height-5);  
  25.         ImageIO.write(bi, "png", os);  
  26.     }  
  27. }<strong>  
  28. </strong>  
效果



二:升级版(转帖)

ImgCode.java

[java] view plaincopy
  1. import java.awt.Color;  
  2. import java.awt.Font;  
  3. import java.awt.Graphics;  
  4. import java.awt.Graphics2D;  
  5. import java.awt.RenderingHints;  
  6. import java.awt.geom.AffineTransform;  
  7. import java.awt.image.BufferedImage;  
  8. import java.io.IOException;  
  9. import java.io.OutputStream;  
  10. import java.util.Arrays;  
  11. import java.util.Random;  
  12. import javax.imageio.ImageIO;  
  13.   
  14. public class ImgCode {  
  15.         
  16.     /** 
  17.      * 生成验证码图片 
  18.      * @param width 
  19.      * @param height 
  20.      * @param codeLength 
  21.      * @param os 
  22.      * @throws IOException 
  23.      */  
  24.     public static void outputCodeImg(int width,int height,String code,OutputStream os) throws IOException{  
  25.       
  26.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
  27.         //获取画笔  
  28.         Graphics2D g2 = image.createGraphics();    
  29.         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);    
  30.         Color[] colors = new Color[5];    
  31.         Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,    
  32.                 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,    
  33.                 Color.PINK, Color.YELLOW };    
  34.         float[] fractions = new float[colors.length];    
  35.         Random rand = new Random();   
  36.         for(int i = 0; i < colors.length; i++){    
  37.             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];    
  38.             fractions[i] = rand.nextFloat();    
  39.         }    
  40.         Arrays.sort(fractions);    
  41.           
  42.         g2.setColor(Color.GRAY);// 设置边框色    
  43.         g2.fillRect(00, width, height);    
  44.             
  45.         Color c = getRandColor(200250);    
  46.         g2.setColor(c);// 设置背景色    
  47.         g2.fillRect(02, width, height-4);    
  48.           
  49.         //绘制干扰线    
  50.         Random random = new Random();    
  51.         g2.setColor(getRandColor(160200));// 设置线条的颜色    
  52.         for (int i = 0; i < 20; i++) {    
  53.             int x = random.nextInt(width - 1);    
  54.             int y = random.nextInt(height - 1);    
  55.             int xl = random.nextInt(6) + 1;    
  56.             int yl = random.nextInt(12) + 1;    
  57.             g2.drawLine(x, y, x + xl + 40, y + yl + 20);    
  58.         }    
  59.             
  60.         // 添加噪点    
  61.         float yawpRate = 0.05f;// 噪声率    
  62.         int area = (int) (yawpRate * width * height);    
  63.         for (int i = 0; i < area; i++) {    
  64.             int x = random.nextInt(width);    
  65.             int y = random.nextInt(height);    
  66.             int rgb = getRandomIntColor();    
  67.             image.setRGB(x, y, rgb);    
  68.         }    
  69.           
  70.         shear(g2, width, height, c);// 使图片扭曲    
  71.           
  72.         g2.setColor(getRandColor(100160));    
  73.         int fontSize = height-4;    
  74.         Font font = new Font("Algerian", Font.ITALIC, fontSize);    
  75.         g2.setFont(font);    
  76.          
  77.         char[] chars = code.toCharArray();    
  78.         int verifySize = code.length();  
  79.         for(int i = 0; i < verifySize; i++){    
  80.             AffineTransform affine = new AffineTransform();    
  81.             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (width / verifySize) * i + fontSize/2, height/2);    
  82.             g2.setTransform(affine);    
  83.             //如果上下 左右两边的验证码出现的位置不对,条件4 , 5参数  
  84.             g2.drawChars(chars, i, 1, ((width-10) / verifySize) * i + 5, height/2 + fontSize/2 -2 );    
  85.         }    
  86.             
  87.         g2.dispose();    
  88.         ImageIO.write(image, "jpg", os);    
  89.     }  
  90.     /** 
  91.      * 返回验证码 
  92.      * @return 
  93.      */  
  94.     public static String getCode(int length){  
  95.         Random random = new Random();  
  96.         StringBuffer code = new StringBuffer();  
  97.         for(int i = 0; i < length; i++){  
  98.             int num = random.nextInt(10); //数字  
  99.             char upperCase = (char) (random.nextInt(26)+65); //大写字母  
  100.             String[] s= new String[2];  
  101.             s[0] = num + "";  
  102.             s[1] = upperCase+ "";  
  103.       
  104.             code.append(s[random.nextInt(2)]);  
  105.         }  
  106.         return code.toString();  
  107.     }  
  108.      private static Color getRandColor(int fc, int bc) {    
  109.            Random random = new Random();   
  110.             if (fc > 255)    
  111.                 fc = 255;    
  112.             if (bc > 255)    
  113.                 bc = 255;    
  114.             int r = fc + random.nextInt(bc - fc);    
  115.             int g = fc + random.nextInt(bc - fc);    
  116.             int b = fc + random.nextInt(bc - fc);    
  117.             return new Color(r, g, b);    
  118.         }    
  119.        private static int getRandomIntColor() {    
  120.             Random random = new Random();  
  121.             int[] rgb =  new int[3];   
  122.             for (int i = 0; i < 3; i++) {    
  123.                 rgb[i] = random.nextInt(255);    
  124.             }    
  125.             int color = 0;    
  126.             for (int c : rgb) {    
  127.                 color = color << 8;    
  128.                 color = color | c;    
  129.             }    
  130.             return color;    
  131.         }    
  132.        private static void shear(Graphics g, int w1, int h1, Color color) {    
  133.             shearX(g, w1, h1, color);    
  134.             shearY(g, w1, h1, color);    
  135.         }    
  136.        private static void shearX(Graphics g, int w1, int h1, Color color) {    
  137.            Random random = new Random();  
  138.             int period = random.nextInt(2);    
  139.         
  140.             boolean borderGap = true;    
  141.             int frames = 1;    
  142.             int phase = random.nextInt(2);    
  143.         
  144.             for (int i = 0; i < h1; i++) {    
  145.                 double d = (double) (period >> 1)    
  146.                         * Math.sin((double) i / (double) period    
  147.                                 + (6.2831853071795862D * (double) phase)    
  148.                                 / (double) frames);    
  149.                 g.copyArea(0, i, w1, 1, (int) d, 0);    
  150.                 if (borderGap) {    
  151.                     g.setColor(color);    
  152.                     g.drawLine((int) d, i, 0, i);    
  153.                     g.drawLine((int) d + w1, i, w1, i);    
  154.                 }    
  155.             }    
  156.         
  157.         }    
  158.        private static void shearY(Graphics g, int w1, int h1, Color color) {    
  159.            Random random = new Random();  
  160.             int period = random.nextInt(40) + 10// 50;    
  161.         
  162.             boolean borderGap = true;    
  163.             int frames = 20;    
  164.             int phase = 7;    
  165.             for (int i = 0; i < w1; i++) {    
  166.                 double d = (double) (period >> 1)    
  167.                         * Math.sin((double) i / (double) period    
  168.                                 + (6.2831853071795862D * (double) phase)    
  169.                                 / (double) frames);    
  170.                 g.copyArea(i, 01, h1, 0, (int) d);    
  171.                 if (borderGap) {    
  172.                     g.setColor(color);    
  173.                     g.drawLine(i, (int) d, i, 0);    
  174.                     g.drawLine(i, (int) d + h1, i, h1);    
  175.                 }    
  176.         
  177.             }    
  178.         
  179.         }    
  180. }<strong>  
  181. </strong>  

效果


测试类Test.java

[java] view plaincopy
  1. public class Test{    
  2.     public static void main(String[] args) {  
  3.         try {  
  4.             String code = ImgCode.getCode(5);  
  5.             ImgCode.outputCodeImg(12030, code,  new FileOutputStream(new File("c:/"+code+".jpg")));  
  6.             Img.outputCodeImg(8025, code, new FileOutputStream(new File("c:/"+code+".png")));  
  7.             System.out.println(code);  
  8.         } catch (FileNotFoundException e) {  
  9.             // TODO Auto-generated catch block  
  10.             e.printStackTrace();  
  11.         } catch (IOException e) {  
  12.             // TODO Auto-generated catch block  
  13.             e.printStackTrace();  
  14.         }  
  15.     }  
  16.       
  17. }    
0 0
原创粉丝点击