Convert an image (selected by path) to base64 string

vaj90 picture vaj90 · Jan 24, 2014 · Viewed 221k times · Source

How do you convert an image from a path on the user's computer to a base64 string in C#?

For example, I have the path to the image (in the format C:/image/1.gif) and would like to have a data URI like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. representing the 1.gif image returned.

Answer

Nitin Varpe picture Nitin Varpe · Jan 24, 2014

Try this

using (Image image = Image.FromFile(Path))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}