- package cn.edu.hbcit.util;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import javax.imageio.stream.ImageOutputStream;
- //闂呫劍顭奸弫鎼侇敚
- public class RandomNumUtil {
- private ByteArrayInputStream image;// 閸ユ儳鍎�
- private String str;// 妤犲矁鐦夐惍锟�
- private RandomNumUtil() {
- init();// 閸掓繂顬婇崠鏍х潣閹拷
- }
- /*
- * 閸欐牕绶盧andomNumUtil鐎圭偘绶�
- */
- public static RandomNumUtil Instance() {
- return new RandomNumUtil();
- }
- /*
- * 閸欐牕绶辨宀冪槈閻礁娴橀悧锟�
- */
- public ByteArrayInputStream getImage() {
- return this.image;
- }
- /*
- * 閸欐牕绶遍崶鍓у閻ㄥ嫰鐛欑拠浣虹垳()
- */
- public String getString() {
- return this.str;
- }
- private void init() {
- // 閸︺劌鍞寸�妯硅厬閸掓稑缂撻崶鎹愯杽
- int width = 63, height = 20;
- BufferedImage image = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_RGB);
- // 閼惧嘲褰囬崶鎯ц埌娑撳﹣绗呴弬锟�
- Graphics g = image.getGraphics();
- // 閻㈢喐鍨氶梾蹇旀簚缁拷
- Random random = new Random();
- // 鐠佹儳鐣鹃懗灞炬珯閼癸拷
- g.setColor(getRandColor(200, 250));
- g.fillRect(0, 0, width, height);
- // 鐠佹儳鐣剧�妞剧秼
- g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
- // 闂呭繑婧�禍褏鏁�55閺夆�鍏遍幍鎵殠閿涘奔濞囬崶鎹愯杽娑擃厾娈戠拋銈堢槈閻椒绗夐弰鎾诡枂閸忚泛鐣犵粙瀣碍閹恒垺绁撮崚锟�
- g.setColor(getRandColor(160, 200));
- 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);
- }
- // 閸欐牠娈㈤張杞伴獓閻㈢喓娈戠拋銈堢槈閻拷6娴e秵鏆熺�锟�
- String sRand = "";
- for (int i = 0; i < 4; i++) {
- String rand = String.valueOf(random.nextInt(10));
- sRand += rand;
- // 鐏忓棜顓荤拠浣虹垳閺勫墽銇氶崚鏉挎禈鐠炩�鑵�
- g.setColor(new Color(20 + random.nextInt(110), 20 + random
- .nextInt(110), 20 + random.nextInt(110)));
- // 鐠嬪啰鏁ら崙鑺ユ殶閸戠儤娼甸惃鍕杹閼硅尙娴夐崥宀嬬礉閸欘垵鍏橀弰顖氭礈娑撹櫣顬岀�鎰亰閹恒儴绻庨敍灞惧娴犮儱褰ч懗鐣屾纯閹恒儳鏁撻幋锟�
- g.drawString(rand, 13 * i + 6, 16);
- }
- // 鐠у锟芥宀冪槈閻拷
- this.str = sRand;
- // 閸ユ崘钖勯悽鐔告櫏
- g.dispose();
- ByteArrayInputStream input = null;
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- try {
- ImageOutputStream imageOut = ImageIO
- .createImageOutputStream(output);
- ImageIO.write(image, "JPEG", imageOut);
- imageOut.close();
- input = new ByteArrayInputStream(output.toByteArray());
- } catch (Exception e) {
- System.out.println("妤犲矁鐦夐惍浣告禈閻楀洣楠囬悽鐔峰毉閻滀即鏁婄拠顖ょ窗" + e.toString());
- }
- this.image = input;/* 鐠у锟介崶鎯у剼 */
- }
- /*
- * 缂佹瑥鐣鹃懠鍐ㄦ纯閼惧嘲绶遍梾蹇旀簚妫版粏澹�
- */
- private Color getRandColor(int fc, int bc) {
- 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);
- }
- }
Java的随机验证码生成类
最新推荐文章于 2024-01-23 16:35:41 发布