图片验证码 java_java生成图片验证码
时间: 2023-08-31 20:07:17 浏览: 109
生成图片验证码可以使用 Java 的 BufferedImage 类和 Graphics 类,以下是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class ImageCode {
private int width = 100; // 验证码图片的宽度
private int height = 40; // 验证码图片的高度
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', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'2', '3', '4', '5', '6', '7', '8', '9'};
public ImageCode() {
createImageCode();
}
public void createImageCode() {
int x = 0, fontHeight = 0, codeY = 0;
int red = 0, green = 0, blue = 0;
x = width / (codeCount + 2);
fontHeight = height - 5;
codeY = height - 8;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.createGraphics();
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 8);
int ye = ys + random.nextInt(height / 8);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawLine(xs, ys, xe, ye);
}
StringBuilder randomCode = new StringBuilder();
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i + 1) * x, codeY);
randomCode.append(strRand);
}
code = randomCode.toString();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code;
}
}
```
使用时可以直接调用 `ImageCode` 类的 `getBuffImg` 方法获取生成的验证码图片,调用 `getCode` 方法获取验证码字符串。例如:
```java
ImageCode imageCode = new ImageCode();
BufferedImage buffImg = imageCode.getBuffImg();
String code = imageCode.getCode();
```
阅读全文