【问题标题】:Retrieving an Image from SQL using C# to an asp:Image使用 C# 从 SQL 检索图像到 asp:Image
【发布时间】:2013-01-28 03:44:28
【问题描述】:

我正在尝试从 SQL Server 2008 Express 检索图像并将其插入<ASP:Image>。我尝试过使用MemoryStream,但我似乎无法正确使用它。

我现在的 C# 代码如下所示:

  try
  {
     con.Open();

     SqlCommand sqlGetStep1 = new SqlCommand("staff_getStep1", con);
     {
         sqlGetStep1.CommandType = CommandType.StoredProcedure;
         sqlGetStep1.Parameters.Add(new SqlParameter("@taskID", Convert.ToInt16(taskID)));
         SqlDataReader step1 = sqlGetStep1.ExecuteReader();

         //Check if username exists
         if (step1.Read())
         {
            step1Text = (string)step1["step1Text"];
            step1Image = (byte)step1["step1Image"];

          }//if 
          else
          {
             step1Text = "null";
             step1Image = 0;
          }//else

           }//sqlDeleteNotification

       }//try
       catch (SqlException sqlEx)
       {
           lblSQLError.Visible = true;
           lblSQLError.Text = sqlEx.Message.ToString();
        }//catach sql
        catch (Exception ex)
       {
           lblError.Visible = true;
           lblError.Text = ex.ToString();

       }//Catch exception
       finally
       {
           con.Close();
       }//Finally

我想在其中显示图像的 aspx 代码如下所示:

<asp:Panel runat="server" ID="pnlStep1" Visible="false" CssClass="NormalText">        
   <asp:Label runat="server" ID="lblStep1Text" Text="Step 1 Instruction: "></asp:Label>
   <asp:TextBox runat="server" ID="txtStep1Text" Text="" ReadOnly="true"></asp:TextBox>
   <asp:Label runat="server" ID="lblStep1Image" Text="Step 1 Image: "></asp:Label>
   <asp:Image runat="server" ID="imgStep1" ImageUrl="" Height="100px" Width="100px"/>
</asp:Panel>

任何帮助将不胜感激:)

【问题讨论】:

  • 你的意思是byte[],而不是byte
  • 代码现在看起来像:变量 - byte[] step1Image = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }; - 从 SQL 中获取图像值 (byte[])。进行转换: MemoryStream ms = new MemoryStream(step1Image); // 流 fs = FileUpload1.PostedFile.InputStream; BinaryReader br = new BinaryReader(ms);字节[] 字节 = br.ReadBytes((Int32)ms.Length); string base64String = Convert.ToBase64String(bytes, 0, bytes.Length); imgStep1.ImageUrl = "data:image/png;base64," + base64String;
  • 感谢您的帮助:)

标签: c# asp.net sql-server-2008-express


【解决方案1】:

您需要有一个单独的 url,它获取要交付的图像的 id(在本例中为步骤 id),并将内容作为具有正确 MIME 类型的结果交付。使用此方法的 url 作为asp:Image 的 url。通常,您会将此(在 WebForms 中)实现为 HttpHandler。见How to return an image as the response in ASP.NET

【讨论】:

    猜你喜欢
    • 2010-10-16
    • 2018-01-19
    • 2018-07-28
    • 2012-03-03
    • 1970-01-01
    • 2019-09-24
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多