简体   繁体   English

我如何显示图像到ImageButton asp.net C#

[英]How can i display an image to ImageButton asp.net c#

This Updates the database by inserting the image file to avatar column. 这通过将图像文件插入到头像列来更新数据库。 The uploading to database works but it wont display in image button. 上载到数据库有效,但不会显示在图像按钮中。

protected void imgProfile_Click(object sender, ImageClickEventArgs e)
{
    SqlConnection connection = null;
    try
    {
        FileUpload img = (FileUpload)ofd;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = ofd.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        // Insert the employee name and image into db
        string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnectionString2"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        string sql = "UPDATE Users SET Avatar = ('" + imgByte + "') OUTPUT INSERTED.User_ID WHERE Username = ('" + Session["UserName"].ToString() + "')";
        SqlCommand cmd = new SqlCommand(sql, connection);

        int id = Convert.ToInt32(cmd.ExecuteScalar());
        userid.Text = "<script>alert('" + String.Format("Employee ID is" +" "+ id) + "')</script>";
        userid.Visible = false;

        //display
        imgProfile.ImageUrl = "~/Handler1.ashx?id=" + id;
    }
    catch
    {
        //lblResult.Text = "There was an error";
    }
    finally
    {
        connection.Close();
    }

This Part is where i am stuck on it wont display it on image button please help 这部分是我卡住的地方,不会在图像按钮上显示它,请帮忙

public void ProcessRequest(HttpContext context)
{
    Int32 empno;
    if (context.Request.QueryString["User_ID"] != null)
        empno = Convert.ToInt32(context.Request.QueryString["User_ID"]);
    else
        throw new ArgumentException("No parameter specified");

    context.Response.ContentType = "image/jpeg";
    Stream strm = ShowEmpImage(empno);
    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 empno)
{

    string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnctionString2"].ConnectionString;
    SqlConnection connection = new SqlConnection(conn);
    string sql = "SELECT Avatar FROM Users WHERE User_ID = @ID";
    SqlCommand cmd = new SqlCommand(sql, connection);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@ID", empno);
    connection.Open();
    object img = cmd.ExecuteScalar();
    try
    {
        return new MemoryStream((byte[])img);
    }
    catch
    {
        return null;
    }
    finally
    {
        connection.Close();
    }
}

This is the .aspx file 这是.aspx文件

    <script type="text/javascript" >
    function clk() {
        var ofd = document.getElementById('<%=ofd.ClientID%>');
        ofd.click();
    }

<asp:Label ID="lblUser" runat="server"></asp:Label>
<asp:Label ID="userid" runat="server"></asp:Label>


<div style="width:100%;">
    <asp:ImageButton ID="imgProfile" CssClass="img-circle img img-rounded" runat="server" Height="100px" Width="100px" OnClientClick="clk();" OnClick="imgProfile_Click"></asp:ImageButton>
    <div style="display:none">
    <asp:FileUpload ID="ofd" runat="server" />
</div>
</div>
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgProfile.ImageUrl = "data:image/png;base64," + base64String;

Try the above lines in a method that fetches the image bytes from the database. 在一种从数据库中获取图像字节的方法中,尝试上述几行。 To do this you don't even need ashx handler. 为此,您甚至不需要ashx处理程序。 Hope it will help you out. 希望它会帮助你。

To make it better way, add this method in your class and call it to take the bytes from the database after we save it to database. 为了使其更好,请在您的类中添加此方法并在将其保存到数据库后调用该方法从数据库中获取字节。

public string GetImageAsByte64String(int empno)
{

string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnctionString2"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT Avatar FROM Users WHERE User_ID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
    byte[] imgByte = (byte[])img;
    string base64String = Convert.ToBase64String(imgByte , 0, imgByte.Length);
    return  ("data:image/png;base64," + base64String);

}
catch
{
    return null;
}
finally
{
    connection.Close();
}
}

Later call this method as below to assign to your ImageUrl property of the imageButton. 稍后按如下所示调用此方法以分配给imageButton的ImageUrl属性。

//display
imgProfile.ImageUrl = GetImageAsByte64String(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能在asp.net中循环的ImageButton中添加方法,又如何在C#端对星星进行分组? - How can i add a method to ImageButton which is in loop in asp.net also how can i group the stars in c# side? 如何在asp.net C#中将按钮更改为图像按钮 - how to change a button into a imagebutton in asp.net c# 如何在 asp.net 中显示存储在.network 上的图像 (c#) - How to display image stored on the network in asp.net (c#) 如何在asp.net c#中的另一个文本框中拆分电子邮件ID并显示@之前的文本 - how can i split email id and display the text before @ in another textbox in asp.net c# C#ASP.net使用ImageButton填充GridView - C# ASP.net Populate GridView with ImageButton C#/ ASP.Net-ImageButton OnClick CodeBehind函数 - C#/ASP.Net - ImageButton OnClick CodeBehind function C#:如何将Memory stream设置为asp.net图像控件的source属性? - C# :How can i set Memory stream as the asp.net image control's source property? 如何使用C#将位图分配给ASP.NET中的Image控件? - How can I assign a bitmap to a Image control in asp.net using c#? 如何在C#/ ASP.NET中的http://someurl/myimage.jpg中检查图像是否存在 - How can I check if an Image exists at http://someurl/myimage.jpg in C#/ASP.NET 如何使用 ASP.NET C# 动态地将图像添加到 Gridview 数据绑定中 - How can I add image into Gridview Databound dynamically using ASP.NET C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM