C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ToBase64String: This method is where the work happens. We pass in a byte array (the image data itself) and it returns a Base 64 string.
Tip: The Base 64 image data can be used in a Data Uri inside an HTML web page, or in any other text document.
C# program that converts byte array to Base64 string
using System;
using System.IO;
class Program
{
static void Main()
{
// The path of the image.
string image = @"C:\programs\coin.jpg";
// ... Read in bytes of image.
byte[] data = File.ReadAllBytes(image);
// ... Convert byte array to Base64 string.
string result = Convert.ToBase64String(data);
// ... Write Base64 string.
Console.WriteLine("ENCODED: " + result);
}
}
Output
ENCODED: /9j/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCggKDw0QE
[Truncated]
Here: We encode an image to base 64, and then put that encoded data into an HTML file. To body element has a background image.
Steps: Modify the file name to point to an image on your disk. Adjust the output file name. Then open the HTML file in a browser.
C# program that creates data URI image in HTML
using System;
using System.IO;
class Program
{
static void Main()
{
// Update this path.
string image = @"C:\Codex\i\2d-adventurers-map-background.jpg";
byte[] data = File.ReadAllBytes(image);
// Get html string containing image.
string result = @"<html><body style=""background:url(data:image/jpeg;base64," +
Convert.ToBase64String(data) +
@"""></body></html>";
// Write the string.
File.WriteAllText(@"C:\programs\image.html", result);
Console.WriteLine("[DONE]");
}
}
Output
[DONE]