免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 946 | 回复: 0
打印 上一主题 下一主题

Java 生成随机验证码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-10 16:11 |只看该作者 |倒序浏览
今天写了一个生成随机验证码的程序。源码如下,import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.util.Random;import javax.imageio.ImageIO;/** * CodeImageGenerator.java *  * @author        Andy Lu * @version       1.0 */public final class CodeImageGenerator {    private final static int DEF_WIDTH = 60;    private final static int DEF_HEIGHT = 20;        private String code;    private int width;    private int height;        private BufferedImage image;        public CodeImageGenerator() {        this(DEF_WIDTH, DEF_HEIGHT);    }        public CodeImageGenerator(int width, int height) {        this.width = width;        this.height = height;        generateCodeImage();    }        private void generateCodeImage() {                // create the image        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);                Graphics g = image.getGraphics();                // set the background color                g.setColor(new Color(0xDCDCDC));            g.fillRect(0, 0, width, height);                // draw the border        g.setColor(Color.black);        g.drawRect(0, 0, width - 1, height - 1);                // set the font        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));        // create a random instance to generate the codes        Random random = new Random();                // make some confusion        for (int i = 0; i             int x = random.nextInt(width);             int y = random.nextInt(height);            g.drawOval(x, y, 0, 0);        }                // generate a random code        for (int i = 0; i             String rand = String.valueOf(random.nextInt(10));            code += rand;            g.drawString(rand, 13*i+6, 16);        }                g.dispose();    }        public BufferedImage getImage() {        return image;    }        public String getCode() {        return code;    }        public static void main(String[] args) throws Exception {        File imgFile = new File("codeImage.jpeg");        CodeImageGenerator cig = new CodeImageGenerator();        ImageIO.write(cig.getImage(), "JPEG", imgFile);    }}
- Andy (eroclu@gmail.com) 2006-06-20


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/22624/showart_153743.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP