3

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.

Timo
  • 263
  • 3
  • 8
SoManyGoblins
  • 5,605
  • 8
  • 45
  • 65

1 Answers1

0

First solution works correctly but I think your problem is about how to read array byte not how to convert the array to bitmap.
I've used that solution many times. The difference between my solution and your solution is how to read the file and convert it to an array.

I simply use:

System.IO.File.ReadAllBytes(filepath)
Timo
  • 263
  • 3
  • 8
Rev
  • 2,269
  • 8
  • 45
  • 75