java生成图片验证码示例程序
程序员文章站
2023-12-20 16:28:46
复制代码 代码如下:<%@ page language="java" contenttype="text/html; charset=utf-8" &nbs...
复制代码 代码如下:
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>登陆页面</title>
<script type="text/javascript">
function refresh() {
loginform.image.src = "creatimage.jsp";
}
</script>
</head>
<body>
<h1>欢迎登陆本系统</h1><br>
<form action="" method = "post" name="loginform">
<label>账号:<input name="username" type="text" /></label><br>
<label>密码:<input name="password" type="password" /></label><br>
<label>验证码:<input name="code" type="text" /></label>
<!-- 将验证码当做图片处理 -->
<img name="image" border="0" src="creatimage.jsp" onclick="refresh()" />
<input type="submit" value="登陆" />
</form>
</body>
</html>
复制代码 代码如下:
<%@page import="java.util.random"%>
<%@page import="java.awt.graphics"%>
<%@page import="javax.imageio.*"%>
<%@page import="java.awt.*"%>
<%@page import="java.awt.image.bufferedimage"%>
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<%
final char[] str = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int width=100,height=60;
bufferedimage bi = new bufferedimage(width,height,
bufferedimage.type_int_rgb);
graphics g = bi.getgraphics();
g.setcolor(new color(200,200,200));
g.fillrect(0, 0, width, height);
random rnd = new random();
stringbuffer sb = new stringbuffer("");
//产生四位数的字母数字验证码,各个数字的颜色也随即
for(int i=0; i<4; i++) {
int num = rnd.nextint(str.length);
color c = new color(rnd.nextint(256),
rnd.nextint(256),rnd.nextint(256));
g.setcolor(c);
g.setfont(new font("", font.bold+font.italic, 20));
g.drawstring(str[num]+"", 10, 17);
sb.append(str[num]);
}
//划干扰线
for(int i=0; i<10; i++) {
color c = new color(rnd.nextint(256),
rnd.nextint(256),rnd.nextint(256));
g.setcolor(c);
g.drawline(rnd.nextint(width), rnd.nextint(height),
rnd.nextint(width), rnd.nextint(height));
}
string s = new string(sb);
/*
若是产生四位数字,则nextint(8999) + 1000;
然后string.valueof转换为string
*/
//验证码存入session里,方便在登陆校检页比对
session.setattribute("image",s);
//输出到页面
imageio.write(bi,"jpeg",response.getoutputstream());
/*
加入下面这两句什么作用呢?
否则报异常: java.lang.illegalstateexception: getoutputstream()
has already been called for this response
不管原因了
*/
out.clear();
out = pagecontext.pushbody();
%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>图片生成</title>
</head>
<body>
</body>
</html>