159

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.

ruffin
  • 16,507
  • 9
  • 88
  • 138
vaj90
  • 1,803
  • 3
  • 17
  • 17

12 Answers12

238

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;
    }
}
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
  • 9
    Why even bother resaving it though? you can just read the file's bytes and convert those. – Nyerguds Feb 01 '18 at 12:43
  • 3
    In my case it was because i wanted to resize the image after it was loaded. – pgee70 Mar 12 '18 at 06:22
  • @Nyerguds I think it's because it needs to be raw format judging by the `image.RawFormat`. – mekb Jul 22 '19 at 11:13
  • 2
    @facepalm42 `RawFormat` isn't an image format specifier; it's a property of the `image` object, which returns which format the image was in when it was _read from file_, meaning in this case, it'd return the gif format. So it changes nothing, except that instead of the actual original file's bytes, you have the bytes of the image as re-saved to gif by the .Net framework. – Nyerguds Jul 23 '19 at 15:03
  • Note that for some reason, .Net does not see animated gifs it loads as paletted images (only happens on animated gif, though it happens with [some types of png](https://stackoverflow.com/q/24074641/395685) too), and when re-saving said "high colour" images to paletted format, it uses a standard Windows 256-color palette. Since animated gifs usually have an optimised palette, this means that any animated gif saved through this process will have its quality horribly degraded. So this setup is definitely not ideal; it's much better to just read the original bytes, as KansaiRobot's answer shows. – Nyerguds Jul 24 '19 at 13:58
  • The example above is not compatible with .net core. – ADM-IT Apr 12 '21 at 09:58
192

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)));
Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21
  • 3
    @Smith, if you mean convert back from base64 to `System.Drawing.Image` you can use st. like this: `var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));` – Arin Ghazarian Jun 28 '14 at 03:10
40

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)));
Ogglas
  • 62,132
  • 37
  • 328
  • 418
10

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();
Jeremy Bell
  • 2,104
  • 1
  • 14
  • 9
8

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.

  • That might give issues if the input is a gif; it re-saves it as the same type (as fetched from `_image.RawFormat`) but exposes the data as mime type `image/jpg` – Nyerguds Jul 24 '19 at 14:05
3

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);
nikunjM
  • 560
  • 1
  • 7
  • 21
3

This code works well with me on DotNet Core 6

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

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

        // In my case I didn't find the part "data:image/png;base64,", so I added.
        return $"data:image/png;base64,{base64String}";
    }
}
Mohammed Osman
  • 3,688
  • 2
  • 27
  • 25
2

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

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;
}
Matěj Štágl
  • 870
  • 1
  • 9
  • 27
  • 1
    You can replace this whole thing by just `return Convert.ToBase64String(File.ReadAllBytes(path));`. No need to even involve `System.Drawing` at all. – Nyerguds Sep 08 '20 at 17:18
0

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);
Jamil Moughal
  • 19
  • 1
  • 6
0

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);
}
BobbyTables
  • 4,481
  • 1
  • 31
  • 39
-5

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
Pao Xu
  • 1
  • 1