1 context.Response.ContentType = "image/jpeg"; 2 //生成隨機的中文驗證碼 3 string yzm = "人口手大小多少上中下男女天地會反清復明楊中科小寶雙兒命名空間語現在明天來多個的我山東河北南固安北京南昌東海西安是沙河高教園學" 4 + "木禾上下土個八入大天人火文六七兒九無口日中了子門月不開四五目耳頭米見白田電也長山出飛馬鳥雲公車牛羊小少巾牙尺毛又心手水廣升足" 5 + "走方半巴業本平書自已東西回片皮生裡果幾用魚今正雨兩瓜衣來年左右萬百丁齊冬說友話春朋高你綠們花紅草爺親節的歲行古處聲知多忙洗真認父掃" 6 + "母爸寫全完關家看笑著興畫會媽合奶放午收女氣太早去亮和李語秀千香聽遠唱定連向以更後意主總先起干明趕淨同專工才級隊螞蟻前房空網詩黃林閉" 7 + "童立是我朵葉美機她過他時送讓嗎往吧得蟲很河借姐呢呀哪誰涼怕量跟最園臉因陽為光可法石找辦許別那到都嚇叫再做象點像照沙海橋軍竹苗井面鄉" 8 + "忘想念王這從進邊道貝男原愛蝦跑吹樂地老快師短淡對熱冷情拉活把種給吃練學習非苦常問伴間共伙汽分要沒孩位選北湖南秋江只幫星請雪就球跳玩" 9 + "桃樹剛蘭座各帶坐急名發成動晚新有麼在變什條"; 10 Random r = new Random(); 11 string validCode = ""; 12 for (int i = 0; i < 4; i++) 13 { 14 int number = r.Next(0, yzm.Length); 15 validCode += yzm[number]; 16 } 17 18 //畫圖 19 using(Bitmap b = new Bitmap(150, 30)) 20 { 21 using (Graphics g = Graphics.FromImage(b)) 22 using(Font f = new Font("宋體", 20)) 23 { 24 g.Clear(Color.Yellow);//清除整個繪畫面並填充指定背景色 25 g.DrawString(validCode, f, Brushes.Red, new PointF(0, 0));//開始繪制 26 //前景點 27 for (int i = 0; i < 100; i++) 28 { 29 int x = r.Next(0, 150); 30 int y = r.Next(0, 30); 31 b.SetPixel(x, y, Color.Red); 32 } 33 //後景線 34 for (int i = 0; i < 100; i++) 35 { 36 int x = r.Next(0, 150); 37 int y = r.Next(0, 30); 38 g.DrawLine(Pens.Red, x, y, x + 1, y + 1); 39 } 40 } 41 b.Save(context.Response.OutputStream, ImageFormat.Jpeg);//保存到輸出流中 42 }