How to convert image to base64 string

Why do you need to convert?

You may have html file with image and do not want to keep your image file separately with html file. In such case you can convert image to base64 string and use it in html file. There can be many other use case where you need to covert image to base64 string

CODE In C#

 static void Main(string[] args)  
{
     string imagePath=@"E:\temp\background.png";  
     string Base64String = GetBase64StringForImage(imagePath);  
     Console.WriteLine(Base64String);
}
protected static string GetBase64StringForImage(string imgPath)  
{
      byte[] imageBytes = System.IO.File.ReadAllBytes(imgPath);  
      string base64String = Convert.ToBase64String(imageBytes);  
      return base64String;  
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.