ToBase64String
Any kind of binary data (like a JPG image) can be stored in a Base 64 representation. This encoding is within the range of ASCII text.
In C# programs we can use the Convert type that is found in the System
namespace. We directly invoke the ToBase64String
method. We can pass in a byte
array.
Consider this short program. We have a path to an image on the local disk (the image is named "coin.jpg" but you can change the file name and the path).
ToBase64String()
is where the work happens. We pass in a byte
array (the image data itself) and it returns a Base 64 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); } }ENCODED: /9j/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCggKDw0QE [Truncated]
We can place the image directly in an HTML file with the data URI syntax. This eliminates a HTTP request when a user views the page with the image.
using System; using System.IO; class Program { static void Main() { // Update this path. string image = @"C:\perls\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]"); } }[DONE]
ReadAllBytes
In C# programs the easiest way to get binary data for an image (or other similar file) is to use the ReadAllBytes
method. It receives a path, and returns a byte
array.
The Convert.ToBase64String
method is used in the creation of this website. It returns the same results as a similar method for the Go language.