在ASP.NET中读取Sql Server2005中的图片

在ASP.NET中读取Sql Server2005中的图片

索引:读取    Sql Server2005     图片

      完成将图片以二进制方式存储到数据库中之后,最重要的工作就是读取并运用,这些工作相对老说较为轻松,我们只需要简单的将它读取出来,并写入页面就可以了。但是如果只是这样简单的读写,那么注定我们的图片没有太大的用途,因此本篇文章第二部分将说明如何运用这些数据库中的图片。

1:读取并显示图片。

        新建web页面:getPic.aspx,在这个页面不需要任何控件,打开其代码页面getPic.aspx.cs,在其Page_load中输入以下代码:

public partial class getPic : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strConn = @"server=localhost\sqlexpress;database=test;user id=sa;password=sa123";
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand cmd = conn.CreateCommand();
        int id = Convert.ToInt32(Request.QueryString["id"]);
        string sql = "select * from imgtest where id=" + id;
        //string sql = "select * from imgtest where id=1"; //这一行用来测试该页面
        cmd.CommandText = sql;
        try
        {
            conn.Open();
            SqlDataReader myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                Response.ContentType = myReader["info"].ToString();
                Response.BinaryWrite((byte[])myReader["img"]);
            }
            conn.Close();
            //Response.Write("the img output is ok!");
        }
        catch (Exception ex)
        {
            Response.Write("the img output is error:" + ex.ToString());
        }
    }
}

       在上述代码中,有两点需要注意:一是Response.ContentType,我们将该属性设置为了图片的类型,二是使用BinaryWrite方法将从数据库中读取的二进制数据写入页面,Response.BinaryWrite((byte[])myReader["img"]),在这据代码中需要将读取的内容转换为字节数组,因为BinaryWrite方法接受byte[]类型。

对该方法有疑问,可以参考MSDN:http://msdn2.microsoft.com/zh-cn/library/system.web.httpresponse_methods.aspx

2:扩展使用从数据库读取的图片。

       完成上面一步后,虽然我们已经能够将图片显示在页面中,但并没有太大的用途,毕竟每次只能显示一张图片,并且我们不能够有效地对他进行控制。现在新建一个web页面usePic.aspx,在该页面中拖入一个Image控件,将其ImageUrl设定为getPic.aspx?id=1。其html源码如下所示:
<form id="form1" runat="server">
    <div>
        使用数据库中的图片:<br /><br />
        <asp:Image ID="Image1" runat="server" ImageUrl="getPic.aspx?id=1" />
    </div>
</form>


        在浏览器中运行该页面进行测试,其效果如下所示:


       从这一方法中我们可以看出,通过Image控件我们可以对从数据库中读取的图片进行有效地控制(如读取第几幅,显示大小及位置等),并且可以通过程序有效地进行显示控制等等。这样以来其就具有了传统上传图片并使用的特点,真正实现了扩展。

       这种方法的具体使用方式可以参看我的另一篇文章:ASP.NET图文验证吗的实现

原文地址:https://www.cnblogs.com/no7dw/p/1720874.html