当前位置:编程学习 > JAVA >>

Java实现网页验证码

package tk.donghongyujava.util;

import java.awt.Color;

public class RandomImage {

	private final static int WIDTH = 100;
	private final static int HEIGHT = 30;
	public static Random rd = new Random();

	public static BufferedImage creatImage() {

		// 画出图片
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_BGR);
		// 得到画笔
		Graphics g = image.getGraphics();
		// 设置背景
		drawBackground(g);
		// 绘制边框
		drawBorder(g);
		//绘制内容
		drawContent(g);
		// 绘制干扰
		drawDisturb(g);
		
		
		return image;
	}

	private static void drawContent(Graphics g) {
		// TODO Auto-generated method stub
		String  con="qwertyuiopasdfgjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<4;i++){
			int index=rd.nextInt(con.length());
			char str=con.charAt(index);
			sb.append(str+" ");
		}
		g.setColor(Color.black);
		g.setFont(new Font("Gungsuh",Font.BOLD, 20));
		g.drawString(sb.toString(), 15, 20);
	}
	

	private static void drawDisturb(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.BLUE);

		for (int i = 0; i < 4; i++) {
			int x1 = rd.nextInt(WIDTH);
			int y1 = rd.nextInt(HEIGHT);
			int x2 = rd.nextInt(WIDTH);
			int y2 = rd.nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
		}
		g.setColor(Color.red);
		g.drawOval(30, 20, 2, 2);

	}

	private static void drawBorder(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.yellow);

		g.drawRect(0, 0, WIDTH - 2, HEIGHT - 2);
	}

	private static void drawBackground(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.green);
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}

}

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,