java web中图片验证码功能的简单实现方法
程序员文章站
2024-03-12 15:24:02
用户在注册网站信息的时候基本上都要数据验证码验证。那么图片验证码功能该如何实现呢?
大概步骤是:
1.在内存中创建缓存图片
2.设置背景色
3.画边框
4.写字母...
用户在注册网站信息的时候基本上都要数据验证码验证。那么图片验证码功能该如何实现呢?
大概步骤是:
1.在内存中创建缓存图片
2.设置背景色
3.画边框
4.写字母
5.绘制干扰信息
6.图片输出
废话不多说,直接上代码
package com.lsgjzhuwei.servlet.response; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.ioexception; import java.util.random; import javax.imageio.imageio; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; /** * servlet implementation class verificationcode */ @webservlet(asyncsupported = true, urlpatterns = { "/verificationcode" }) public class verificationcode extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public verificationcode() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub int width = 120; int height = 30; //创建一张内存中的缓存图片 bufferedimage bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb); ///背景色 //通过graphics绘制图像 graphics graphics = bufferedimage.getgraphics(); //设置颜色 graphics.setcolor(color.yellow); //填充 graphics.fillrect(0, 0, width, height); ///画边框 graphics.setcolor(color.blue); graphics.drawrect(0, 0, width-1, height-1); //写字母 string content = "abcdefghijklmnopqrstuvwxyzabcedfghijklmnopqrstuvwxyz1234567890"; random random = new random(); //设置字体颜色 graphics.setcolor(color.red); //设置字体及大小 graphics.setfont(new font("宋体", font.bold, 20)); int x=20; int y=20; for(int i = 0; i < 4; i++) { int index = random.nextint(content.length()); char letter = content.charat(index); graphics.drawstring(letter+" ", x, y); x = x+20; } //绘制干扰线 int x1; int x2; int y1; int y2; graphics.setcolor(color.light_gray); for(int i = 0;i <50;i++) { x1=random.nextint(width); x2=random.nextint(width); y1=random.nextint(height); y2=random.nextint(height); graphics.drawline(x1, y1, x2, y2); } //将图片输出到浏览器 //将内存的图片通过浏览器输出流输出成jpg图片 imageio.write(bufferedimage, "jpg", response.getoutputstream()); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub } }
以上这篇java web中图片验证码功能的简单实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。