java 生成验证码

 代码如下:

package com.part01;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
/**
 * 
 * @author ASUS
 * 随机生成验证码
 */
public class RandomImgAction  {
	
	//定义验证码的长、宽
	private static int width=200;
	private static  int height=40;
	
	public static void main(String[] args) throws IOException {
		
		//利用BufferedImage类创建一张图片
		BufferedImage bi=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		//利用Graphics对图片进行绘制
		Graphics g=bi.createGraphics();
		
		//设置背景色
		g.setColor(new Color(220,220,220));
		g.fillRect(0, 0, width, height);
		
		//设置边框
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width-1, height-1);
		
		//画随机线
		Random random=new Random();
		for(int i=0;i<500;i++) {
			
			int startx=random.nextInt(width);
			int starty=random.nextInt(height);
			int end=random.nextInt(20);
			
			g.setColor(new Color(160,160,160));
			g.drawLine(startx, starty,startx+end,starty+end);
		}
		
		//写验证码
		for(int i=0;i<4;i++) {
			//设置验证码4个值的随机颜色
			int red=random.nextInt(255);
			int green=random.nextInt(255);
			int blue=random.nextInt(255);
			
			int start=random.nextInt(10);
			String num=String.valueOf(random.nextInt(10));
			
			g.setColor(new Color(red,green,blue));
			g.setFont(new Font("微软雅黑", Font.BOLD, 30));
			g.drawString(num,start+i*40+14,start+i*2+30);//y值基数不能给过小,否则数字会向上跑,与上面设置的字体大小有关
		}
		
		//将生成的验证码输出
		ImageIO.write(bi, "png", new File("d://4.png"));
		System.out.println("请在d盘下查看4.png文件");
	}	
		
		
}


生成结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值