java生成验证码代码

下面是自己写的一个生成验证码的代码:

1.4个验证码不在同一位置,

2.美观度可以自己改变。全部由自己设计,

package cn.itcast.zlWeb.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Random;

public class Helper {
	/**
	 * 生成一个验证码图片
	 * 
	 * @param width
	 *            图片宽度
	 * @param height
	 *            图片高度
	 * @return
	 */
	public static BufferedImage getImage(int width, int height)
	{
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);

		Graphics g = image.getGraphics();
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, width, height);

		// 干扰点
		g.setColor(Color.BLUE);

		Random r = new Random();
		for (int i = 0; i < 100; i++) {
			int x = r.nextInt(width) - 2;
			int y = r.nextInt(height) - 2;

			// 画图片上的点
			g.drawOval(x, y, width, height);
		}

		// 写验证码

		char[] arrays = ("123456789abcdefghijklmnopqrstuvwxyz"
				+ "HIJKLMNOPQRSTUVWXYZ").toCharArray();
		g.setColor(Color.RED);

		// 得到验证码
		//StringBuilder sb = new StringBuilder();
		
		g.setFont(new Font("微软雅黑",Font.BOLD,20));
		int x = 20;
		int y = 0;
		
		for (int i = 0; i < 4; i++) {
			int pos = r.nextInt(arrays.length);
			char c = arrays[pos]; //取的随机码
			y = r.nextInt(20)+10;
			x += r.nextInt(20)+5;
			g.drawString(c+"", x, y);
			
		}
		
		
		return image;
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值