Converting images to base64 strings is a common need when transmitting images over the internet. Base64 encoding represents binary data in an ASCII character set, making it suitable for use in environments where binary data may not be supported.
To convert an image from a path on a user's computer to a base64 string, simply follow these steps:
The provided code snippet demonstrates this process:
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 resulting base64 string can be embedded as a data URI using the format data:image/gif;base64,${base64String}, where image/gif represents the image type, and ${base64String} is the base64-encoded image data.
The above is the detailed content of How Can I Convert Images to Base64 Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!