Java写一个输出图片验证码的类,要求参数可控
时间: 2023-02-08 15:48:40 浏览: 47
```java
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.Random;
import javax.imageio.ImageIO;
public class Captcha {
private int width = 100;
private int height = 50;
private int codeCount = 4;
private int lineCount = 20;
private String code = null;
private BufferedImage buffImg = null;
private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
// 验证码类型为仅数字,可以根据需求修改
// private char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public Captcha() {
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
*/
public Captcha(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
* @param codeCount 字符个数
* @param lineCount 干扰线条数
*/
public Captcha(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
int x = 0, fontHeight = 0, codeY = 0;
int red = 0, green = 0, blue = 0;
x = width / (codeCount + 2);//每个字符的宽度
fontHeight = height - 2;//字体的高度
codeY = height - 4;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 生成随机数
Random random = new Random();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建