在C#中将图像数据填充为数据表作为字节数组

时间:2016-07-16 16:46:30

标签: c# asp.net arrays sql-server datatable

所以我填充了数据表但是我需要图像数据的列不起作用。我可以看到填充的表,可以看到它正在读取数据,但不是作为字节数组,也不是显示图像。

public void Bindformview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
            DataTable dt = new DataTable();

            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                FormViewRecipes.DataSource = dt;
                FormViewRecipes.DataBind();
            }
            else
            {
                FormViewRecipes.DataSource = null;
                FormViewRecipes.DataBind();
            }
        }

我知道我需要插入这个代码,或类似的东西,将数据从db" thumbnail varbinary(MAX)"中提取出来。列作为字节流,以获取正确显示图像的字节数组:

 DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";

table.Columns.Add(column); //Add the column to the table.

和此:

 DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);

但我不需要新列或新行,因为那些字段已经存在。 那么如何填写专栏#34; Thumbnail&#34;在数据表中,要显示字节数组数据,在if绑定dt的if语句中,在加载dt的if语句之前,我在哪里插入所述代码?

我是这样写的,如下所示:

dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());

然后把它放进来填写formview image1 ID吗?

                    string strBase64 = Convert.ToBase64String(bytes);
                    formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;

我处于停滞状态,不知道如何做到这一点。 所以要清楚,我已经拥有了具有正确图像信息的数据库,并且可以通过<asp:image id=image1...etc />显示它,其他代码使用此代码在formview之外检索图像,

string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("spGetImageByID", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter paramId = new SqlParameter()
                    {
                        ParameterName = "@Id",
                        Value = Request.QueryString["Id"]
                    };
                    cmd.Parameters.Add(paramId);
                    con.Open();
                    byte[] bytes = (byte[])cmd.ExecuteScalar();

                    string strBase64 = Convert.ToBase64String(bytes);
                    Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                }
            }

但它在<asp:FormView...etc/>中无效,我需要能够将其用于页面格式化。 这就是为什么我正朝着这个方向前进,现在使用数据表。如果您有更好的解决方案,我愿意尝试它,只要它可以在<asp:formview />元素内部使用。谢谢。

1 个答案:

答案 0 :(得分:0)

所以我明白了:

我需要在数据绑定Object o;

之后添加o = dt.Rows[0]["RecipeId"];和此行

喜欢如此:

if (dt.Rows.Count > 0)
                {
                    FormViewRecipes.DataSource = dt;
                    FormViewRecipes.DataBind();
                    //lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
                    o = dt.Rows[0]["RecipeId"];

                }
                else
                {
                    FormViewRecipes.DataSource = null;
                    FormViewRecipes.DataBind();
                }
            }

并调用加载图像:

 string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramId = new SqlParameter()
                {
                    ParameterName = "@RecipeId",
                    Value = o //Object from the datatable

            };
                cmd.Parameters.Add(paramId);
                con.Open();
                byte[] bytes = (byte[])cmd.ExecuteScalar();

                if (bytes != null)
                {
                    string strBase64 = Convert.ToBase64String(bytes);
                    Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                }
                else
                {
                    Image1.ImageUrl = "~/images/NoImageAvail.jpg";
                }
            }

以下代码是否有其他人需要做同样的事情。我将把for / while或for / next组合在一起,以便同时显示多个数据库条目,而不是当前在<asp:forview...></formview>元素设置中一次显示。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;

namespace DB_Test1
{
    public partial class Search_Results_1 : System.Web.UI.Page
    {
        string b;
        Object o;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Search"] != null)
            {
                if (Request.QueryString["Text"] != null)
                {
                    string a = Request.QueryString["Text"];
                    b = a;
                    recipeSearch(a);
                }
            }
        }
        protected void recipeSearch(string a)
        {
            //Search the database
            con.Open();
            try
            {
                SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
                DataTable dt = new DataTable();

                adp.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    FormViewRecipes.DataSource = dt;
                    FormViewRecipes.DataBind();
                    //lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
                    o = dt.Rows[0]["RecipeId"];

                }
                else
                {
                    FormViewRecipes.DataSource = null;
                    FormViewRecipes.DataBind();
                }
            }

            catch (Exception ex)
            {
                //throw new ApplicationException("operation failed!", ex);
            }
            con.Close();
            FormViewRecipes.Visible = true;

            string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramId = new SqlParameter()
                {
                    ParameterName = "@RecipeId",
                    Value = o //Object from the datatable

            };
                cmd.Parameters.Add(paramId);
                con.Open();
                byte[] bytes = (byte[])cmd.ExecuteScalar();

                if (bytes != null)
                {
                    string strBase64 = Convert.ToBase64String(bytes);
                    Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                }
                else
                {
                    Image1.ImageUrl = "~/images/NoImageAvail.jpg";
                }
            }

            Image1.Visible = true;


        }
        protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
        {
            string a = b;
            FormViewRecipes.PageIndex = e.NewPageIndex;
            recipeSearch(a);
        }
    }
}

这是ASPX页面代码:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <hr />
    <div class="row">
        <div class="col-md-8">
            <table>
                <tr>
                    <td>
                        <asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
                    </td>
                    <td>
                        <asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
            onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
             <%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#EFF3FB" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
            <ItemTemplate>
            <table style="border:1px solid #c1c1c1;">
            <tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
                <%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>' 
                   AlternateText='<%# Eval("ThumbnailAltTxt") %>' 
                    Height="100px" Width="100px" />--%></td>
            </tr>
              <tr><td><b>Title:- </b></td><td>
                  <asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
              <tr><td><b>Ingredients:- </b></td><td>
                  <asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>                
              <tr><td><b>Directions:- </b></td><td>
                  <asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
                <tr><td><b>Notes:- </b></td><td>
                  <asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>

                            </table>
            </ItemTemplate>
              <EmptyDataTemplate>
            <table style="border:1px solid #c1c1c1;">
            <tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
            <tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
            <tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
            <tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>

            </table>
            </EmptyDataTemplate>




            </asp:FormView>
                    </td>
                </tr>
            </table>
        </div>
        <div class="col-md-4">
            <p>Ad Space</p>
            <asp:Label ID="lblDataTable" runat="server"></asp:Label>
        </div>
    </div>

</asp:Content>

请记住,我已注释掉<asp:image..../a>元素中的<Asp:formview.../>元素字段并重置我的页面布局,以了解我希望它如何寻找测试。