Tuesday 7 January 2020

Convert image to base 64 string and base 64 string to image in c#

Converting and image to base 64 from an image or from a path or converting a base 64 string to an image is quite easy. We will use MemoryStream to convert them. We will use two simple method one to convert the image to base 64 string and other to convert the base 64 string to image. Image can be saved wherever you want or show them anywhere on the page
Code to convert the image into base 64 string by passing the image page, if you are using asp.net or web page then you need to use Server.MapPath to get the correct image path than absolute path
  1. public String ConvertImageToBase64String(String imagePath)
  2. {
  3.     using (var img = System.Drawing.Image.FromFile(imagePath))
  4.     {
  5.         using (var memStream = new MemoryStream())
  6.         {
  7.             img.Save(memStream, img.RawFormat);
  8.             byte[] imageBytes = memStream.ToArray();
  9.             // Convert byte[] to Base64 String
  10.             string base64String = Convert.ToBase64String(imageBytes);
  11.             return base64String;
  12.         }
  13.     }
  14. }
First we convert the image path into image, then save this image into memory and finally converted into base 64 string.
Now we will write the code to convert the base 64 string into image, we will pass base 64 string as parameter and then convert it into bytes and then to memory string and finally to image.
  1. public System.Drawing.Image Base64StringToImage(string base64String)
  2. {
  3.     byte[] imageBytes = Convert.FromBase64String(base64String);
  4.     var memStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
  5.     memStream.Write(imageBytes, 0, imageBytes.Length);
  6.     var image = System.Drawing.Image.FromStream(memStream);
  7.     return image;
  8. }
If you want to save this image in any folder simple use image.save method to save it.

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...