Encode and decode image file using Base64 in C#

In this article, learn how to encode and decode image file using Base64 in C# code.


Encode and decode image file using Base64 in C#:

using System;
using System.IO;
namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            string encFileText = EncodeImageFileToBase64(@"C:\test.jpg");

            //You can save the 'encFileText' data into any file for future use.

            DecodeImageFileFromBase64(encFileText);

        }

        /// 
        /// Function to encode imagefile into Base64.
        /// 
        public static string EncodeImageFileToBase64(string sFile)
        {
            var fileBytes = File.ReadAllBytes(sFile);

            //Encode image file
            string encFileText = Convert.ToBase64String(fileBytes);

            return encFileText;
        }

        /// 
        /// Function to decode encoded image data into actual image file data and save the image file.
        /// Note: Saving the image file directly into C drive require admin rights.
        /// 
        public static void DecodeImageFileFromBase64(string sEncFileText)
        {
            var decFileBytes = Convert.FromBase64String(sEncFileText);

            File.WriteAllBytes(@"D:\NewImageFile.jpg", decFileBytes);
        }
    }
}



– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Convert Binary into Decimal in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo