javaweb之生成验证

javaweb之生成验证


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

import javax.imageio.ImageIO;

import javax.persistence.Entity;

/**
* 工具类,生成验证码图片
*
*/
@Entity
public class SecurityImage {

/**
* 生成验证码图片
*
* @param securityCode
* 验证码字符
* @return BufferedImage 图片
*/
public static BufferedImage createImage(String securityCode) {

// 验证码长度
int codeLength = securityCode.length();
// 字体大小
int fSize = 20;
int fWidth = fSize + 1;
// 图片宽度
int width = codeLength * fWidth + 20;
// 图片高度
int height = fSize * 2 + 1;

// 图片
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();

// 设置背景色
g.setColor(Color.WHITE);
// 填充背景
g.fillRect(0, 0, width, height);

// 设置边框颜色
g.setColor(Color.LIGHT_GRAY);
// 边框字体样式
g.setFont(new Font("Arial", Font.BOLD, height - 2));
// 绘制边框
g.drawRect(0, 0, width - 1, height - 1);

// 绘制噪点
Random rand = new Random();
// 设置噪点颜色
g.setColor(Color.LIGHT_GRAY);
for (int i = 0; i < codeLength * 6; i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
// 绘制1*1大小的矩形
g.drawRect(x, y, 1, 1);
}

// 绘制验证码
int codeY = height - 10;
// 设置字体颜色和样式
g.setColor(new Color(19, 148, 246));
g.setFont(new Font("Georgia", Font.BOLD, 30));
for (int i = 0; i < codeLength; i++) {
g.drawString(String.valueOf(securityCode.charAt(i)), i * 20 + 10,
codeY);
}
// 关闭资源
g.dispose();

return image;
}

/**
* 返回验证码图片的流格式
*
* @param securityCode
* 验证码
* @return ByteArrayInputStream 图片流
*/
public static ByteArrayInputStream getImageAsInputStream(String securityCode) {

BufferedImage image = createImage(securityCode);
return convertImageToStream(image);
}

/**
* 将BufferedImage转换成ByteArrayInputStream
*
* @param image
* 图片
* @return ByteArrayInputStream 流
*/
private static ByteArrayInputStream convertImageToStream(BufferedImage image) {
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, "JPEG", bos);
byte[] bts = bos.toByteArray();
inputStream = new ByteArrayInputStream(bts);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return inputStream;

}
}

转载于:https://www.cnblogs.com/sxf20/p/6680644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值