Convert Base64 string as Image File

Convert Base64 string as Image File and save the file using file upload in C#.First read the uploaded file using Binary Reader and convert it to Byte Array. Convert the Byte Array to Base64 Encoded string using the Convert.ToBase64String method. Now in order to save the Base64 encoded string as Image File, Convert Base64 Encoded string to Byte Array and Save the Byte Array as Image File.

HTML Code

The following HTML Markup consists of an ASP.Net FileUpload control to upload the Image File and a Button control to trigger the File upload process.

<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
</form>

 C# Code to convert Base64 string as image

Add below code in the button click event.

protected void btnUpload_Click(object sender, EventArgs e)
{
    //***Convert Image File to Base64 Encoded string***//
 
    //Read the uploaded file using BinaryReader and convert it to Byte Array.
    BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
    byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
 
    //Convert the Byte Array to Base64 Encoded string.
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
 
    //***Save Base64 Encoded string as Image File***//
 
    //Convert Base64 Encoded string to Byte Array.
    byte[] imageBytes = Convert.FromBase64String(base64String);
       
    //Save the Byte Array as Image File.
    string filePath = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName));
    File.WriteAllBytes(filePath, imageBytes);
}

The Base64 string is now saved as image file.