从SQL Server数据库显示图像

时间:2013-07-17 06:22:19

标签: c# asp.net image-processing

我将图像作为字节数组存储在SQL Server数据库中,并使用处理程序在网页上显示图像。图像在Internet Explorer上正常显示,但它在chrome和firefox中有些奇怪的字符。

 ÿØÿáExifII*ÿìDuckyPÿáohttp://ns.adobe.com/xap/1.0/ ÿíHPhotoshop 3.08BIMZ%G8BIM%üá‰È·Éx/4b4XwëÿîAdobedÀÿÛ

我的处理程序代码是

if (context.Request.QueryString["id"] != null)
{
   // context.Response.Write(context.Request.QueryString["id"]);
   string dbcon = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;

   SqlConnection con = new SqlConnection(dbcon);
   con.Open();

   SqlCommand cmd = new SqlCommand("select Offers_bigimage from Offers where Offers_OfferId=@empid", con);
   cmd.Parameters.AddWithValue("@empid", context.Request.QueryString["id"].ToString());

   SqlDataReader dr = cmd.ExecuteReader();
   dr.Read();
   context.Response.BinaryWrite((byte[])dr["Offers_bigimage"]);
   dr.Close();
   con.Close();
}
else
{
   context.Response.Write("No Image Found");
}

请帮忙

1 个答案:

答案 0 :(得分:2)

您必须设置图像的内容类型。您可以根据您正在使用的图像类型查找mime类型列表,下面是jpg的示例。注意这一行:

context.Response.ContentType = "image/jpeg";

完整示例

if (context.Request.QueryString["id"] != null)
{
    // context.Response.Write(context.Request.QueryString["id"]);
    string dbcon = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
    SqlConnection con = new SqlConnection(dbcon);
    con.Open();
    SqlCommand cmd = new SqlCommand("select Offers_bigimage from Offers where Offers_OfferId=@empid", con);
    cmd.Parameters.AddWithValue("@empid", context.Request.QueryString["id"].ToString());
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();

    context.Response.ContentType = "image/jpeg";
    context.Response.BinaryWrite((byte[])dr["Offers_bigimage"]);
    dr.Close();
    con.Close();
}
else
{
    context.Response.ContentType = "text/plain";
    context.Response.Write("No Image Found");
}