Author : MD TAREQ HASSAN | Updated : 2020/08/02
What is Base64String
ToBase64String
var str = "quick brown fox jumped over the lazy dog";
var bytes = Encoding.ASCII.GetBytes(str);
var base64String = Convert.ToBase64String(bytes);
//Console.WriteLine(BitConverter.ToString(bytes));
Console.WriteLine(base64String);
Console.WriteLine();
FromBase64String
var base64String = ...
var bytes = Convert.FromBase64String(base64String);
var str = Encoding.ASCII.GetString(bytes);
//Console.WriteLine(BitConverter.ToString(bytes));
Console.WriteLine(str);
Image to Base64String
Get the byte array (byte[]) representation of image, then use Convert.ToBase64String()
byte[] imageArray = File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
Online encoder: https://base64.guru/converter/encode/image
Base64String to Image
To convert a base4 image back to a System.Drawing.Image:
var base64String = ...
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
Online decoder: https://base64.guru/converter/decode/image
Base64String as Image Source
var fooModel = new FooModel();
fooModel.AvatarIcon = Convert.ToBase64String(File.ReadAllBytes(@"image file path"));
// ... ... ...
Using in Blazor component
<img src="data:image/html;base64,@AvatarIcon" alt="Avatar Icon of @LastName" />