2014.11.28测试题,验证码生成及模拟

来源:互联网 发布:网络侦探练哪些 编辑:程序博客网 时间:2024/05/17 09:13

1.

package com.hechao;import java.awt.Color;import java.awt.Graphics;public class MyUtil {private MyUtil(){}/** * 随机验证码 * @return */public static String indentfyCode(){int choise = (int) (Math.random() * 3);switch(choise){case 0 :char c1 = 'A';int random1 = (int) (Math.random() * 26);c1 += random1;return c1 + "";case 1 :char c2 = 'a';int random2 = (int) (Math.random() * 26);c2 += random2;return c2 + "";default :return (int)(Math.random() * 10) + "";}}/** * 随机颜色 * @return */public static Color randomColor(){int r = (int) (Math.random() * 256);int g = (int) (Math.random() * 256);int b = (int) (Math.random() * 256);Color color = new Color(r, g, b);return color;}/** * 画干扰线 * @param g 画笔 */public static void drawRandomLine(Graphics g){int x1 = 25;int y1 = (int) (Math.random() * 100 + 35);int x2 = 275;int y2 = (int) (Math.random() * 100 + 35);g.drawLine(x1, y1, x2, y2);}}


2.

package com.hechao;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Stroke;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import javax.swing.JFrame;/** * 验证码窗口 * @author 何超 * */@SuppressWarnings("serial")public class MyFrame extends JFrame {private int identfyingCodeLength = 6;private String[] str = new String[identfyingCodeLength];private BufferedImage bi = new BufferedImage(300, 150, 1);public MyFrame(){this.setTitle("验证码");this.setSize(300, 150);this.setResizable(false);this.setLocationRelativeTo(null);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent arg0) {initialised();}});initialised();}/** * 初始化 * 产生验证码 */private void initialised(){for(int i = 0; i < identfyingCodeLength; i++){str[i] = MyUtil.indentfyCode();repaint();}}@Overridepublic void paint(Graphics g) {//双缓冲Graphics offG = bi.getGraphics();super.paint(offG);Graphics2D g2d = (Graphics2D) offG;//保存现场Stroke oldStroke = g2d.getStroke();Color oldColor = g2d.getColor();//改变画笔,画20根干扰直线for(int i = 0; i < 20; i++){offG.setColor(MyUtil.randomColor());g2d.setStroke(new BasicStroke(1));MyUtil.drawRandomLine(offG);}//画验证码for (int i = 0; i < identfyingCodeLength; i++) {offG.setColor(MyUtil.randomColor());offG.setFont(new Font("Consolas", Font.BOLD, 42));offG.drawString(str[i], 50 + i * 35, 100);}g.drawImage(bi, 0, 0, null);//恢复现场g2d.setStroke(oldStroke);g2d.setColor(oldColor);}public static void main(String[] args) {new MyFrame().setVisible(true);}}


0 0
原创粉丝点击