I am trying to read an image into Base64 format using .Net Core 2.2 and it throws
ArgumentException: Image format is unknown. System.Drawing.Image.FromFile(string filename, bool useEmbeddedColorManagement)
The filePath is correct, and I have double and triple checked that the file exists.
I have attempted naming my PNGs with both upper and lowercase extension.
This does not happen locally on windows, but once the application is deployed to linux is happens. The code in question is below.
public static string ImageToBase64(string filePath)
{
System.Diagnostics.Debug.WriteLine($"File Path for Image: {filePath}");
string base64String;
using (var image = Image.FromFile(Path.GetFullPath(filePath)))
{
using (var ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
image.Dispose();
byte[] imageBytes = ms.ToArray();
base64String = Convert.ToBase64String(imageBytes);
imageBytes = null;
ms.Dispose();
}
}
GC.Collect();
return base64String;
}
EDIT
I also tried using a filestream with bitmap.
public static string ImageToBase64(string filePath)
{
string base64String;
using(var fs = new FileStream(filePath,FileMode.Open))
using (var image = new Bitmap(fs))
{
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png);
image.Dispose();
byte[] imageBytes = ms.ToArray();
base64String = Convert.ToBase64String(imageBytes);
imageBytes = null;
ms.Dispose();
}
}
GC.Collect();
return base64String;
}
This throws the following exception:
Exception thrown: 'System.ArgumentException' in System.Drawing.Common.dll: 'Image format is unknown.' Stack trace:
at System.Drawing.Image.InitializeFromStream(Stream stream) at System.Drawing.Bitmap..ctor(Stream stream)
While I am still unsure of why Image.FromFile and using Bitmap didn't work, I managed to get it working by using ImageSharp from SixLabors.
Working code is below.
public static string ImageToBase64(string filePath)
{
string base64String;
using (var image = SixLabors.ImageSharp.Image.Load(filePath))
{
using (var ms = new MemoryStream())
{
image.Save(ms, new PngEncoder());
image.Dispose();
byte[] imageBytes = ms.ToArray();
base64String = Convert.ToBase64String(imageBytes);
imageBytes = null;
ms.Dispose();
}
}
GC.Collect();
return base64String;
}