ToBase64String (Data URI Image)
This page was last reviewed on Feb 22, 2023.
Dot Net Perls
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.
byte Array
An example. 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).
Important ToBase64String() 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.
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); } }
Data URI. 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.
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.
Detail 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.
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]"); } }
Notes, 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.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 22, 2023 (edit).
© 2007-2024 Sam Allen.