从sqlServer的image字段获取并显示图像示例(ASPNET2.0)
发布时间:2020-12-12 15:34:10 所属栏目:MsSql教程 来源:网络整理
导读:第一种方法: 要两个页,第一个页面放Image控件(A.aspx);另一个页面用 Response.BinaryWrite((byte[])users.PhotoData)显示image类型图片(B.aspx); A.aspx: asp:Image ID="ManagerPhoto" runat="server" Width="50px" / A.aspx.cs: ? ManagerPhoto.ImageU
第一种方法:
要两个页,第一个页面放Image控件(A.aspx);另一个页面用 Response.BinaryWrite((byte[])users.PhotoData)显示image类型图片(B.aspx);
A.aspx: <asp:Image ID="ManagerPhoto" runat="server" Width="50px" /> A.aspx.cs: ? ManagerPhoto.ImageUrl = "B.aspx?ID=" + ID.ToString(); B.aspx.cs: protected void Page_Load(object sender,EventArgs e) ? ? ? ? { ? ? ? ? ? ? Users users = _org.GetUsersInfomationByID(Convert.ToInt32(Request.QueryString["ID"])); ? ? ? ? ? ? Response.BinaryWrite((byte[])users.PhotoData); ? ? ? ? } 第二种方法: <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Web; using System.Configuration; public class Handler : IHttpHandler?? { ??? ??? public bool IsReusable?? { ??????? get?? { ??????????? return true; ??????? } ??? } ??? public void ProcessRequest(HttpContext context)?? { ??????? // Set up the response settings ??????? context.Response.ContentType = "image/jpeg"; ??????? context.Response.Cache.SetCacheability(HttpCacheability.Public); ??????? context.Response.BufferOutput = false; ??????? Stream stream = null; ??????? if (context.Request.QueryString["employeeID"] != "")?? { ??????????? stream = GetPhoto(context.Request.QueryString["employeeID"]); ??????? } ??????? const int buffersize = 1024 * 16; ??????? byte[] buffer = new byte[buffersize]; ??????? int count = stream.Read(buffer,buffersize); ??????? while (count > 0)?? { ??????????? context.Response.OutputStream.Write(buffer,count); ??????????? count = stream.Read(buffer,buffersize); ??????? } ??? } ??? public Stream GetPhoto(string photoId)?? { ??????? SqlConnection myConnection = new SqlConnection("server=192.168.3.17;database=mypeople;user id='sa';password='"); ??????? SqlCommand myCommand = new SqlCommand ??????????? ("SELECT [照片] FROM [people] WHERE [职工编号]=@PhotoID", ??????????? myConnection); ??????? myCommand.CommandType = CommandType.Text; ??????? myCommand.Parameters.Add(new SqlParameter("@PhotoID",photoId)); ??????? myConnection.Open(); ??????? object result = myCommand.ExecuteScalar(); ??????? ??????? try?? { ??????????? return new MemoryStream((byte[])result); ??????? } ??????? catch (ArgumentNullException e)?? { ??????????? return null; ??????? } ??????? finally?? { ??????????? myConnection.Close(); ??????? } ??? } } /* ----------------------引用方法--------------------------------------- ?? <asp:Image ID="imgPhoto" ForeColor =Red runat="server" ??????? ImageUrl='<%# "Handler2.ashx?employeeID=" + Eval("职工编号") %>' ??????? AlternateText="该员工无照片" Height="248px" Width="188px" /> ?-----------------------------------------------------------------------*/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |