Convert an image (selected by path) to base64 string

C#ImageBase64

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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;
    }
}

Solution 2 - C#

Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:

byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);

To convert a base64 image back to a System.Drawing.Image:

var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));

Solution 3 - C#

Since most of us like oneliners:

Convert.ToBase64String(File.ReadAllBytes(imageFilepath));

If you need it as Base64 byte array:

Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));

Solution 4 - C#

This is the class I wrote for this purpose:

public class Base64Image
{
    public static Base64Image Parse(string base64Content)
    {
        if (string.IsNullOrEmpty(base64Content))
        {
            throw new ArgumentNullException(nameof(base64Content));
        }

        int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);

        string dataLabel = base64Content.Substring(0, indexOfSemiColon);

        string contentType = dataLabel.Split(':').Last();

        var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;

        var fileContents = base64Content.Substring(startIndex);

        var bytes = Convert.FromBase64String(fileContents);

        return new Base64Image
        {
            ContentType = contentType,
            FileContents = bytes
        };
    }

    public string ContentType { get; set; }

    public byte[] FileContents { get; set; }

    public override string ToString()
    {
        return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
    }
}

var base64Img = new Base64Image { 
  FileContents = File.ReadAllBytes("Path to image"), 
  ContentType="image/png" 
};

string base64EncodedImg = base64Img.ToString();

Solution 5 - C#

You can easily pass the path of the image to retrieve the base64 string

public static string ImageToBase64(string _imagePath)
    {
        string _base64String = null;
    
        using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
        {
            using (MemoryStream _mStream = new MemoryStream())
            {
                _image.Save(_mStream, _image.RawFormat);
                byte[] _imageBytes = _mStream.ToArray();
                _base64String = Convert.ToBase64String(_imageBytes);
    
                return "data:image/jpg;base64," + _base64String;
            }
        }
    }

Hope this will help.

Solution 6 - C#

You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.

byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
        
string base64ImageRepresentation = Convert.ToBase64String(imageArray);

Solution 7 - C#

That way it's simpler, where you pass the image and then pass the format.

private static string ImageToBase64(Image image)
{
    var imageStream = new MemoryStream();
    try
    {           
        image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
        imageStream.Position = 0;
        var imageBytes = imageStream.ToArray();
        var ImageBase64 = Convert.ToBase64String(imageBytes);
        return ImageBase64;
    }
    catch (Exception ex)
    {
        return "Error converting image to base64!";
    }
    finally
    {
      imageStream.Dispose;
    }
}

Solution 8 - C#

Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing before Image as one might be using that class from other namespace defaultly.

public static string ImagePathToBase64(string path)
{
    using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    using MemoryStream m = new MemoryStream();
    image.Save(m, image.RawFormat);
    byte[] imageBytes = m.ToArray();
    tring base64String = Convert.ToBase64String(imageBytes);
    return base64String;
}

Solution 9 - C#

The following piece of code works for me:

string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);

Solution 10 - C#

The reverse of this for the googlers arriving here (there is no SO quesion/answer to that)

public static byte[] BytesFromBase64ImageString(string imageData)
{
	var trunc = imageData.Split(',')[1];
	var padded = trunc.PadRight(trunc.Length + (4 - trunc.Length % 4) % 4, '=');
	return Convert.FromBase64String(padded);
}

Solution 11 - C#

Something like that

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvaj90View Question on Stackoverflow
Solution 1 - C#Nitin VarpeView Answer on Stackoverflow
Solution 2 - C#Arin GhazarianView Answer on Stackoverflow
Solution 3 - C#OgglasView Answer on Stackoverflow
Solution 4 - C#Jeremy BellView Answer on Stackoverflow
Solution 5 - C#sumith madhushanView Answer on Stackoverflow
Solution 6 - C#nikunjMView Answer on Stackoverflow
Solution 7 - C#Elias FilipeView Answer on Stackoverflow
Solution 8 - C#Matěj ŠtáglView Answer on Stackoverflow
Solution 9 - C#Jamil MoughalView Answer on Stackoverflow
Solution 10 - C#BobbyTablesView Answer on Stackoverflow
Solution 11 - C#Pao XuView Answer on Stackoverflow