【问题标题】:Retrieving images from SQL Server 2008 and displying it in a image controller of asp.net从 SQL Server 2008 检索图像并将其显示在 asp.net 的图像控制器中
【发布时间】:2013-08-02 13:12:03
【问题描述】:

我在 SQL Server 2008 中有一个表 images,它包含两列 imageidimage。我可以使用FileUpload 控制器和图像将图像插入image 列,并将图像转换为二进制形式进行存储。现在我想在与图像 id 对应的图像框中显示图像。我正在使用一个文本框让用户输入id,并使用一个按钮来执行显示命令。

public void ShowImage()
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["anu"].ToString();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select ID,Image from Images where ID=" + txtid.Text;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        con.Open();
        SqlDataReader dreader = cmd.ExecuteReader();
        dreader.Read();
        Context.Response.BinaryWrite((byte[])dreader["image"]);
        dreader.Close();
        con.Close();
}

此代码运行良好,但它会将图像加载到单独的页面中,但我需要将其显示在特定的图像框中。我的前端是 ASP.NET。如果哪位知道答案,请帮帮我。

【问题讨论】:

  • 这不是 SQL,因为 SQL 正在运行。您的问题是 asp.net,因此请根据需要更改标签

标签: asp.net sql image sql-server-2008


【解决方案1】:

而不是Response.Write 将字节数组存储在会话中

Session["image"]=(byte[])dreader["image"];

将此作为image的来源

byte[] imgSrc=(byte[])Session["image"]
string imgSrcStr= Convert.ToBase64String(imgSrc);
string imageSrc = string.Format("data:image/gif;base64,{0}", imgSrcStr);

In the view:

<img src='"<%=imageSrc%>"' />

或者只是在你的函数中完成所有这些操作,而不是 Response

【讨论】:

    【解决方案2】:

    首先,您应该真正在查询(或存储过程)中使用参数

    您可以从二进制数据中创建一个图像,并使用正确的图像格式将其保存到输出流中。

    var ms = new MemoryStream((byte[])dreader["image"]);
    var image = Image.FromStream(ms);
    Context.Response.ContentType = "image/jpeg"; //or your actual imageformat
    image.Save(Context.Response.OutputStream, format);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 2012-03-03
      • 1970-01-01
      • 2021-04-15
      • 2023-03-30
      • 2019-11-18
      • 1970-01-01
      相关资源
      最近更新 更多