How do you convert an image to a base64 string in C#?
For example, I have the path to the image C:/image/1.gif
and would like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..
returned.
How do you convert an image to a base64 string in C#?
For example, I have the path to the image C:/image/1.gif
and would like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..
returned.
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;
}
}
Get the byte array (byte[]
) representation of 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 base4 image back to a System.Drawing.Image:
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
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)));
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();
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);
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
try
{
var imageStream = new MemoryStream();
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!";
}
}
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.
Although the more complicated answer is ok, I find that this is much better
var base64String= Convert.ToBase64String(File.ReadAllBytes(pathOfPic));
It is simple, you don't need to resave and handles different formats
You can convert it like this
string test = @"C:/image/1.gif";
byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(test);
string base64String = System.Convert.ToBase64String(bytes);
Console.WriteLine("Base 64 string: " + base64String);
Output
QzovaW1hZ2UvMS5naWY=
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