Convert Image to Base64 String
Converting an image to a base64 string allows you to embed images within other data, such as HTML or JavaScript. In this context, we'll explore how to convert an image from a file path to a base64 string in C#.
Solution:
To convert an image to a base64 string in C#, follow these steps:
Code Example:
using System; using System.Drawing; using System.IO; namespace ImageToBase64 { class Program { static void Main(string[] args) { string path = @"C:\Users\User\Documents\test.jpg"; // Create a data URI string base64String = ToBase64(path); Console.WriteLine(base64String); } /// <summary> /// Converts an image to a base64 string. /// </summary> /// <param name="path">The file path of the image.</param> /// <returns>A base64 string representing the image.</returns> public static string ToBase64(string path) { using (Image image = Image.FromFile(path)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); string base64String = Convert.ToBase64String(imageBytes); return base64String; } } } } }
The above is the detailed content of How to Convert an Image File Path to a Base64 String in C#?. For more information, please follow other related articles on the PHP Chinese website!