如何使用 C# 在 ASP.NET 中将二进制图像显示到 gridview 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19132451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:11:19  来源:igfitidea点击:

How to display binary images into a gridview in ASP.NET using C#?

c#asp.netimage

提问by Liu Jia Hui

I want to display binary images into a gridview named 'gvExistedCharacter'. I did research about it and many of them suggested to use a handler. However, I have no idea how can I do about it.

我想将二进制图像显示到名为“gvExistedCharacter”的网格视图中。我对此进行了研究,其中许多人建议使用处理程序。但是,我不知道我该怎么做。

FYI: The datatype of the image in the database is image and named 'blueBallImage'. I also want to display its level which is int in the same gridview.

仅供参考:数据库中图像的数据类型是图像并命名为“blueBallImage”。我还想在同一个网格视图中显示它的级别是 int 。

I have tried

我试过了

    SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyCloudGames;Integrated Security=True");

    SqlCommand cmd = new SqlCommand("Select blueBallImage FROM CorrespondingBall", con);
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Connection = con;

    SqlParameter ImageID = new SqlParameter("@characterID", System.Data.SqlDbType.Int);
    ImageID.Value = context.Request.QueryString["characterID"];
    cmd.Parameters.Add(ImageID);
    con.Open();
    SqlDataReader dReader = cmd.ExecuteReader();
    dReader.Read();
    context.Response.BinaryWrite((byte[])dReader["Image"]);
    dReader.Close();
    con.Close();

I received an error "The parameterized query '(@characterID int)Select blueBallImage FROM CorrespondingBall' expects the parameter '@characterID', which was not supplied."

我收到错误消息“参数化查询 '(@characterID int)Select blueBallImage FROM CorrespondingBall' 需要参数 '@characterID',但未提供该参数。”

采纳答案by Satinder singh

You can use handler to display image in gridview , your html markup look like inside

您可以使用处理程序在 gridview 中显示图像,您的 html 标记看起来像里面

Gridview ItemTemplateset image control src as src=~/ShowImage.ashx?id=" + id

Gridview ItemTemplate将图像控件 src 设置为 src=~/ShowImage.ashx?id=" + id

where ShowImage.ashxis your handler which return MemoryStream((byte[])img);

ShowImage.ashx你的处理程序在哪里返回 MemoryStream((byte[])img);

Here my one similar article how to get binary data and display as image

这是我的一篇类似文章如何获取二进制数据并显示为图像

Blog Article: Convert Binary data to image, Save and retrieve image from binary data asp.net c#

博客文章:将二进制数据转换为图像,从二进制数据中保存和检索图像 asp.net c#

In your case your querystring is characterID

在您的情况下,您的查询字符串是 characterID

so your image src would be src=~/ShowImage.ashx?id=" + characterID

所以你的图像 src 将是 src=~/ShowImage.ashx?id=" + characterID



Updated Answer:

更新答案:

Html Markup:

Html 标记:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="CharacterID">
            <ItemTemplate>
                <asp:Label ID="lblid" runat="server" Text='<%# Bind("characterID") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="GameLevel">
            <ItemTemplate>
                <asp:Label ID="lblglevel" runat="server" Text='<%# Bind("gameLevel") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ShowImage.ashx?getID="+Eval("characterID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code behind:

后面的代码:

protected void Page_Load(object sender, EventArgs e)
{        
    DataTable dt = getData();
    GridView1.DataSource = dt;
    GridView1.DataBind();
  }

public  DataTable getData() 
{
  SqlDataAdapter dap = new SqlDataAdapter("select characterID,blueBallImage,gameLevel from CorrespondingBall", cn);
  DataSet ds = new DataSet();
  dap.Fill(ds);
  return ds.Tables[0];
}

Generic handler:Add new generic handler here showIamges.ashx is my generic handler

通用处理程序:在此处添加新的通用处理程序 showIamges.ashx 是我的通用处理程序

public void ProcessRequest(HttpContext context)
 {
    Int32 my_Id;
    if (context.Request.QueryString["getID"] != null)
    {
       my_Id = Convert.ToInt32(context.Request.QueryString["getID"]);
       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(my_Id);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
       while (byteSeq > 0)
        {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
        }
      }
}

public Stream ShowEmpImage(int my_Id)
{
   string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
   SqlConnection connection = new SqlConnection(conn);
   string sql = "select blueBallImage from CorrespondingBall WHERE characterID = @ID";
   SqlCommand cmd = new SqlCommand(sql, connection);
   cmd.CommandType = CommandType.Text;
   cmd.Parameters.AddWithValue("@ID", my_Id);
   connection.Open();
   object img = cmd.ExecuteScalar();
   return new MemoryStream((byte[])img);
 }

回答by Soner G?nül

You want to add @characterIDparameter to your sql command but your command doesn't have a parameter called @characterID.

您想向@characterIDsql 命令添加参数,但您的命令没有名为@characterID.

Remove your parameter process in your code or add @characterID in your sql command which try to match.

删除代码中的参数进程或在尝试匹配的 sql 命令中添加 @characterID 。