Here's the solution I found that works, you might need to modify it for your use case.
I convert the image to png in case it isn't png, then I read the converted image, I do this since png never gave me any error like jpg.
Note that this code isn't really efficient, but it gets the job done as a work around/quick fix
Code:
/// <summary>
/// check if the image exists, or if the image is png
/// if the image is png then I just read the images bytes
/// else I convert the image from whatever type she is to png and then read the bytes
/// </summary>
/// <param name="imageName">the name of the image that is about to be read</param>
/// <returns>byte array of the image data </returns>
public static byte[] GetBytesFromImage(string imageName)
{
byte[] bytes = null;
string imagePath = "..\\..\\Imagens";
imageName = imageName == "" ? "some_default_image.jpg" : imageName;
string fpath = imagePath + imageName;
if (File.Exists(fpath) && imageName.EndsWith("png"))
{
using (MemoryStream ms = new MemoryStream())
using (FileStream imageStream = new FileStream(fpath, FileMode.Open, FileAccess.Read))
{
imageStream.CopyTo(ms);
bytes = ms.ToArray();
}
}
else
{
using (MemoryStream image = new MemoryStream())
using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(fpath))
using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height))
using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage))
{
gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel);
bmpNewImage.Save(image, ImageFormat.Png);
bytes = image.ToArray();
}
}
return bytes;
}
/// <summary>
/// Get the instance of a MigraDoc.DocumentObjectModel.Shapes.Image from byte[]
/// using XImage from PdfSharp to set the width and height automatically.
/// </summary>
/// <param name="img">byte array of the image data</param>
/// <returns>instance of MigraDoc.DocumentObjectModel.Shapes.Image</returns>
public static MigraDoc.DocumentObjectModel.Shapes.Image GetImageInstance(byte[] img)
{
MigraDoc.DocumentObjectModel.Shapes.Image image = null;
using (MemoryStream stream = new MemoryStream(img))
using (PdfSharp.Drawing.XImage imageAux = PdfSharp.Drawing.XImage.FromStream(stream))
{
image = new MigraDoc.DocumentObjectModel.Shapes.Image("base64:" + Convert.ToBase64String(img));
image.Width = imageAux.PointWidth;
image.Height = imageAux.PointHeight;
}
return image;
}