In my app, I can use either XImage.FromFile() or XImage.FromStream() as needed.
If I use XImage.FromFile(), everything seems to be OK, including at least PNG, JPG, and TGA formats.
However, as a job might make use of the same image dozens or hundreds of times, I wanted to be able to cache the images once read off of the disk. To do this I load the images once and store the bitmaps in a dictionary cache. Then when I want to embed them in the PDF, I extract the saved image from the cache and do a Gfx.DrawImage.
Here's the code that did that properly using .NET Framework (using the Bitmap X case):
Code:
XImage Image;
switch (ImageObj)
{
case Bitmap X:
{
using MemoryStream ImageStream = new MemoryStream();
X.Save(ImageStream, ImageFormat.Bmp);
Image = XImage.FromStream(ImageStream);
}
break;
case Stream X:
{
Image = XImage.FromStream(X);
X.Dispose();
}
break;
case string X:
{
Image = XImage.FromFile(X);
}
break;
default:
throw new FormatException();
}
/* draw it */
Gfx.DrawImage(Image, (int)Left, (int)Bottom, (int)Width, (int)Height);
This fails all the time in .NET Core and .NET 5.0.
if I pull the MemoryStream declaration outside the switch case, then things work fine for PNG images in .NET 5.0. JPG and TGA images still don't work:
Code:
XImage Image;
using MemoryStream ImageStream = new MemoryStream();
switch (ImageObj)
{
case Bitmap X:
{
X.Save(ImageStream, ImageFormat.Bmp);
Image = XImage.FromStream(ImageStream);
}
break;
case Stream X:
{
Image = XImage.FromStream(X);
X.Dispose();
}
break;
case string X:
{
Image = XImage.FromFile(X);
}
break;
default:
throw new FormatException();
}
/* draw it */
Gfx.DrawImage(Image, (int)Left, (int)Bottom, (int)Width, (int)Height);