Wednesday, 10 August 2016

Convert Image to byte array and byte to image in ASP.NET C#

Convert Image to byte and then display in Asp.Net C#:

Suppose you are facing problem in showing image from folder to asp.net Image control. Then use below code to display image instant.

Reason behind using this code:

Suppose you have images in folder and path in database. then just pass path in this code and it will get image from folder using this path and then first it will convert into byte and then will directly assign to display to the image control

e.g:

System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(@"C:/FolderName/abc.jpg"));
                            byte[] bytes;
                            using (MemoryStream ms = new MemoryStream())
                            {
                                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                                bytes = ms.ToArray();                            
                            }
                            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                            Image1.ImageUrl = "data:image/png;base64," + base64String;
                            img.Dispose();


Convert image from Fileupload to byte and then display in ASP.Net C#

Reason behind using this code:

Suppose you want to upload new image to replace existing image then due to postback effect system does not show the new
image. In that case below code will first convert image into byte then assign to imageurl

e.g:

string imgType = System.IO.Path.GetExtension(FUploadImg.FileName);
                    int imgSize = FUploadImg.PostedFile.ContentLength;
                 
                    byte[] imgbyte = new byte[imgSize];
                    HttpPostedFile img = FUploadImg.PostedFile;
                    img.InputStream.Read(imgbyte, 0, imgSize);

string base64String = Convert.ToBase64String(imgbyte, 0, imgbyte.Length);
Image2.ImageUrl = "data:image/png;base64," + base64String;



                         
                            

1 comment: