显示SQL Server数据库中的图像

本文关键字:图像 数据库 SQL Server 显示 | 更新日期: 2023-09-27 18:23:34

我将图像作为字节数组存储在SQL Server数据库中,并使用处理程序在网页上显示图像。图片可以在InternetExplorer上正常显示,但也有一些是铬和萤火虫中的奇怪字符。

 ÿØÿá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");
}

请帮助

显示SQL Server数据库中的图像

您必须设置图像的内容类型。根据您使用的图像类型,您可以查找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");
}