Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind an image in c# using byte array

protected void Button2_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string ext = Path.GetExtension(filename);
            if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
            {

                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

                Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;
            }
            else
            {
                Response.Write("<script>alert('unsupported format of photo file');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "');</script>");
        }
    }
}
like image 921
Udit Sharma Avatar asked Dec 09 '22 10:12

Udit Sharma


2 Answers

Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

            Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;

This code is working well ..

like image 61
Udit Sharma Avatar answered Dec 11 '22 09:12

Udit Sharma


I assume you are trying to display image with base64 string in an System.Web.UI.WebControls.Image.

first, create a client JavaScript function to set src attribute of your <img /> tag:

function setImageData(imageBase64) {
    document.getElementById("imageId").src = "data:image/png;base64," + imageBase64;
}

then, Invoke that method by

Response.Write("<script>setImageData("+ base64String +")</script>");
like image 39
lastr2d2 Avatar answered Dec 11 '22 10:12

lastr2d2