后台文件:
1using system;
2using system.data;
3using system.configuration;
4using system.collections;
5using system.drawing;
6using system.web;
7using system.web.security;
8using system.web.ui;
9using system.web.ui.webcontrols;
10using system.web.ui.webcontrols.webparts;
11using system.web.ui.htmlcontrols;
12
13public partial class default2 : system.web.ui.page
14{
15 protected void page_load(object sender, eventargs e)
16 {
17 if(!this.ispostback)
18 {
19 this.genimg(this.gencode(4));
20 }
21
22 }
23 //产生随机字符串
24 private string gencode(int num)
25 {
26 string[] source={"0","1","2","3","4","5","6","7","8","9",
27 "a","b","c","d","e","f","g","h","i","j","k","l","m","n",
28 "o","p","q","r","s","t","u","v","w","x","y","z"};
29 string code="";
30 random rd=new random();
31 for(int i=0;i < num;i++)
32 {
33 code += source[rd.next(0,source.length)];
34 }
35 return code;
36 }
37
38 //生成图片
39 private void genimg(string code)
40 {
41 bitmap mypalette = new bitmap(60, 20);//定义一个画板
42
43 graphics gh = graphics.fromimage(mypalette);//在画板上定义绘图的实例
44
45 rectangle rc = new rectangle(0, 0, 60, 20);//定义一个矩形
46
47 gh.fillrectangle(new solidbrush(color.blue), rc);//填充矩形
48 gh.drawstring(code, new font("宋体", 16), new solidbrush(color.white), rc);//在矩形内画出字符串
49
50 mypalette.save(response.outputstream, system.drawing.imaging.imageformat.jpeg);//将图片显示出来
51
52 session["validatecode"] = code;//将字符串保存到session中,以便需要时进行验证
53
54 gh.dispose();
55 mypalette.dispose();
56 }
57
58}
html文件:
加入一个html控件image即可
<%@ page language="c#" autoeventwireup="true" codefile="default2.aspx.cs" inherits="default2" %>
<img src="default2.aspx" />
新闻热点
疑难解答
图片精选