Hey, I am trying to load an Image
control from a byte array, I've tried multiple solutions found online (particularly this site) but nothing seems to work.
My main goal was to obtain an ImageSource
from the byte array and return it from a converter.
I've tried:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(lBytes);
bi.EndInit();
But this fails with:
NotSupportedException
No imaging component suitable to complete this operation was found.
Also tried first loading a Bitmap
and from there try to get the ImageSource
.
using (MemoryStream lMem = new MemoryStream(lBytes))
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
System.Drawing.Bitmap b = (System.Drawing.Bitmap)tc.ConvertFrom(lBytes);
lResult = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
b.GetHbitmap(),
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
b.Dispose();
}
But this fails on the ConvertFrom
with "Parameter is not valid."
All of this when loading a valid PNG file in my filesystem.
I am running out of ideas, any clue?
Thanks.
Edit:
Alright, the problem was my way of loading the file...
I was using
using (FileStream lFileStream = new FileStream(pFilePath, FileMode.Open))
{
using (StreamReader lReader = new StreamReader(lFileStream))
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
string lString = lReader.ReadToEnd();
bf.Serialize(ms, lString);
ms.Seek(0, 0);
lImage = ms.ToArray();
}
lResult = new Graphic(lImage);
}
}
But then read that I could use:
lImage = File.ReadAllBytes(pFilePath);
And that's it.
Thank you.