(c#流的概念)写了一段验证码的程序。流的概念至今不理解。请大家帮忙讨论一下!
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
public partial class yanzhengma1 : System.Web.UI.Page
{
private string getvali(int numcount)
{
string strsvali = "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";
string[] valiarray = strsvali.Split(',');
string returnnum = "";
int nums = -1;
Random vrand = new Random();
for (int n = 1; n < numcount; n++)
{
if (nums != -1)
{
vrand = new Random(n * nums * unchecked((int)DateTime.Now.Ticks));
}
int t = vrand.Next(35);
nums = t;
returnnum += valiarray[t];
}
Session["Valid"] = returnnum;
return returnnum;
}
private void createimage(string validatenum)
{
if (validatenum == null || validatenum.Trim() == string.Empty)
return;
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(validatenum.Length * 12 + 10, 22);//生成图像
Graphics g = Graphics.FromImage(image);//定义一个绘图画面
try
{
Random random = new Random();
g.Clear(Color.White);//清除画面并以背景色填充
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Coral), x1, y1, x2, y2);//绘制连接坐标的线条
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Green, 1.2f, true);
g.DrawString(validatenum, font, brush, 2, 2);//font:定义文字的格式。brush:渐变工具。2,2:是文字到图片边框的距离
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));//表示分配给指定像素指定的颜色
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);//绘制一个矩形
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string getnums = getvali(5);
createimage(getnums);
}
}
}
这段代码中后面的几句
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();//清除缓存中流的输出
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
大家能详细解释一下吗?什么是流?为什么要用到流来传输数据?输出文字的时候为什么没有涉及到流的问题?另外,为什么要清除缓存区中流的输出?刚接触流的概念 大家别笑话!
[解决办法]
所谓流就是显示流,输入流,而已!response.write封装了流而已