Tuesday, May 25, 2021

Base64 - Encoding and Decoding s String

The following class can be used to encode a string or decode an encoded string. 


   public static class Base64  
   {  
     public static string Encode(this System.Text.Encoding encoding, string textValue)  
     {  
       if (textValue == null)  
       {  
         return null;  
       }  
       try  
       {  
         byte[] textAsBytes = encoding.GetBytes(textValue);  
         return System.Convert.ToBase64String(textAsBytes);  
       }  
       catch (Exception)  
       {  
         return textValue;  
       }        
     }  
     public static string Decode(this System.Text.Encoding encoding, string encodedTextValue)  
     {  
       if (encodedTextValue == null)  
       {  
         return null;  
       }  
       try  
       {  
         byte[] textAsBytes = System.Convert.FromBase64String(encodedTextValue);  
         return encoding.GetString(textAsBytes);  
       }  
       catch (Exception)  
       {  
         return encodedTextValue;  
       }        
     }  
   }  

So, you can refer this as below;



 EncodingForBase64.DecodeBase64(Encoding.UTF8, yourtextvalue);  

Happy coding...

Convert an Image to Base64

Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.

Link to the Question

However we may still need to convert an image to base64 on the way to display our data on HTML page. Assuming you have a class that represent all the necessary details, here is how you can have an additional property to the class that converts images to base64.




     public string imageBase64  
     {  
       get  
       {  
         using (var client = new WebClient())  
         {  
           byte[] dataBytes = client.DownloadData(new Uri(image));  
           string encodedFileAsBase64 = Convert.ToBase64String(dataBytes);  
           return "data:image/jpeg;base64," + encodedFileAsBase64;  
         }  
       }  
     }  

Copy this and try it in your code. it will generate your html image tag as below.


Happy Coding...