java开发_使用BufferedImage生成验证码

前台处理返回的ByteArrayOutputStream


//获取验证码写入ByteArrayOutputStream

ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
String rand = this.getValidateImage(RANGE, 70, 21, 4, 1, os);
req.getSession().setAttribute(KEY, rand);
return new ByteArrayInputStream(os.toByteArray());
} finally {
if (os != null) os.close();
}

//生成验证码方法

public static String getValidateImage(String str, int width, int height, int show, int lineNum, OutputStream output)

{
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, 5);


Font font = new Font("Arial", 0, height - 1);
int distance = 18;
Graphics2D d = (Graphics2D)image.getGraphics();
d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
d.setColor(new Color(0X8FB9EB));
d.fillRect(0, 0, image.getWidth(), image.getHeight());
d.setColor(new Color(random.nextInt(100) + 100, random.nextInt(100) + 100, random.nextInt(100) + 100));
for (int i = 0; i < lineNum; i++) {
d.drawLine(random.nextInt(image.getWidth()), random.nextInt(image.getHeight()), random.nextInt(image.getWidth()),
random.nextInt(image.getHeight()));
}
d.setColor(new Color(0X8FB9EB));
d.setFont(font);
String checkCode = "";


int x = -distance;
for (int i = 0; i < show; i++) {
char tmp = str.charAt(random.nextInt(str.length()));
checkCode = checkCode + tmp;
x += distance;
d.setColor(new Color(random.nextInt(100) + 50, random.nextInt(100) + 50, random.nextInt(100) + 50));
d.drawString(String.valueOf(tmp), x, random.nextInt(image.getHeight() - font.getSize()) + font.getSize());
}
d.dispose();
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
//logger.warn("生成验证码错误.", e);
}
return checkCode;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值