JavaWeb关于简单绘画验证码图像方法
我们先创建一个BufferedImage带缓冲区图像类的方法,代码如下:
private BufferedImage generatePic(int width, int height){
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建图片对象,内存图像的大小为从外部传进的width和height值,BufferedImage.TYPE_INT_RGB表示设置为一个具有8位RGB色彩的图像
Graphics g = image.getGraphics(); //创建画笔对象
Font font = new Font("宋体",Font.PLAIN,48); //创建一个字体类,并通过构造函数设置为宋体,Font.PLAIN(字体风格普通),大小48pt
g.setFont(font); //通过font将以上设置好的字体格式赋予给画笔g
Random random = new Random(); //创建随机数对象
g.setColor(Color.WHITE); // 设置画笔颜色为白色
g.fillRect(0,0,width,height); //对内存图像进行背景填充白色
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//随机字符范围
StringBuilder caption = new StringBuilder(); //用存储随机的4位验证码,用来表单的对比验证
for(int i=1;i<=4;i++) {
int index = random.nextInt(str.length()); //获取随机到字符的下标
char c=str.charAt(index); //提取随机字符
caption.append(c); //进行拼接
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
//对画笔的颜色生成随机
g.drawString(c+"", 25*i, random.nextInt(15)+25); //在内存图像中画出随机到的字符
}
for (int i = 0; i < 10; i++) { //生成干扰线
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
//依旧是随机生成画笔颜色
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
g.drawOval(x, y, x1, y1); //drawOval(x,y,width,height),绘制圆形,x,y分别为包围圆形的矩形左上角端点的x,y轴坐标,width为圆形的宽度,height为圆形的高度
g.drawLine(x, y, x1, y1); //drawLine(x1,y1,x2,y2),这是绘制一条直线,x1,y1为线的最开始的落点位置,x2,y2为线最后画到的位置
for (int j = 0; j < 40; j++) { //生成干扰点
x = random.nextInt(width);
y = random.nextInt(height);
g.drawLine(x, y, x, y);
}
}
return image; //将我们画好的验证码返回去就好了
}
现在我们只需要通过generatePic(宽度,高度)这个方法调用就好了,例:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, IOException {
ImageIO.write(generatePic(100,50),"JPEG",resp.getOutputStream());
//通过ImageIO的方法将对象输出,输出的图片后缀名是JPEG,并且以Response输出流输出到页面上
}