代码如下:
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文件");
}
}
生成结果: