Step 0:
Add <img src="defaultpic.jpg" runat="server" id="imgSoftLogo" width="50" height="50">
Step 1: On Upload Image Click Event
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
// checking the file exists in <asp:FileUpload>
if (btnFileUpload.HasFile == true )
{
// acceptable extentions
List<string> extentions = new List<string> { ".jpg", ".gif", ".png" };
// if file extention exists in acceptable extention
if (extentions.Contains( Path.GetExtension(btnFileUpload.FileName).ToLower()))
{
// get the directory path complete path to save image into asp .net web folder
String filePath = Server.MapPath(@"~/SoftwareImages/" + btnFileUpload.FileName);
// saving the pic to folder
btnFileUpload.SaveAs(filePath);
// converting the pic
image_base64String = ConvertImageTo_base64String(filePath);
imgSoftLogo.Src = @"data:image/gif;base64," + image_base64String;
Session["image"] = image_base64String;
}
}
}
catch (Exception ex) { }
}
Step 2: Add Function to convert the File to image_base64String;
public string ConvertImageTo_base64String(string path)
{
using (System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
image_base64String = Convert.ToBase64String(imageBytes);
}
}
return image_base64String;
}
public string image_base64String { get; set; }
Step 3: Once Uploaded the pic will display on <Img> then save it to database.
software.SoftwareImage = Session["image"].ToString();
Step 4: On Page Load
1) loading from database if existed
imgSoftLogo.Src = @"data:image/gif;base64," + software.SoftwareImage;
2) if we are updating a new software and we have not updated the image yet and we also do not need to update the image so we will do the followings
// take the defaultpic.jpg
string path = Server.MapPath(imgSoftLogo.Src);
image_base64String = ConvertImageTo_base64String(path);
Session["image"] = image_base64String;