微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从sqlServer的image字段获取并显示图像示例ASPNET2.0

第一种方法
要两个页,第一个页面放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" />  -----------------------------------------------------------------------*/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐