Convert an Image to Base64 String in C#
Converting an image from a local file path to a base64 string in C# enables you to embed the image's data directly within your code. This is particularly useful for scenarios like sending images via email, displaying them within web content, or storing them in a database.
To achieve this conversion, you can leverage the following steps:
Use the Image.FromFile method to load the image from the specified path on the user's computer. For example, if the image is located at the path C:/image/1.gif, you would write:
using (Image image = Image.FromFile(@"C:/image/1.gif")) { // ... }
Create a MemoryStream object to capture the image's data in a buffer. Save the image to the memory stream using the Image.Save method, specifying the image's original format:
using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); }
Convert the byte array representing the image data to a base64 string using the Convert.ToBase64String method:
string base64String = Convert.ToBase64String(imageBytes);
The resulting base64String is a representation of the image data in base64 format, which can be used as needed. For example, you can embed it within a data URI like:
data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..
The above is the detailed content of How to Convert an Image to a Base64 String in C#?. For more information, please follow other related articles on the PHP Chinese website!