0

I have to convert BitmapImage (JPEG inside) to byte[] and then back.

Here is my code:

using System.IO;
using System.Windows.Media.Imaging;

public class CImageConverter
  {
    //
    public BitmapImage ByteArray_To_BitmapImage(byte[] _binaryData)
    {
      BitmapImage _bitmapImage = new BitmapImage();
      //
      _bitmapImage.BeginInit();
      _bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
      _bitmapImage.StreamSource = new MemoryStream(_binaryData);
      _bitmapImage.EndInit();
      //
      return _bitmapImage;
    }

    //
    public byte[] BitmapImage_To_ByteArray(BitmapImage _bitmapImage)
    {
      byte[] bytes;
      //
      using(MemoryStream ms = new MemoryStream())
      {
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(_bitmapImage));
        encoder.Save(ms);
        bytes = ms.ToArray();
      }
      //
      return bytes;
    }
  }

It seems that BitmapImage_To_ByteArray working properly.

But ByteArray_To_BitmapImage throwing NotSupportedException in EndInit() method.

The message is (translated with web-translator):

Could not locate the image processing component which is suitable to complete this operation.

I found similar questions on the internet, but the answers do not work. The usual answer is "I tried your code - I have everything working fine."

I also found this suggestion, but did not understood, how to use it.

Thanks for your help!

Community
  • 1
  • 1
  • 2
    Actually, your code works. Perhaps you have somehow corrupted the buffer that you pass to ByteArray_To_BitmapImage. That said, I'd suggest to replace BitmapImage by BitmapSource (the base class) in order to make your methods more usable. And why this ugly leading underscore on some of your identifiers? – Clemens Oct 16 '14 at 12:56
  • 1
    Made the conversion on the spot there and back (why did not I think of that?) - and all went well! You are right, the problem is in the transmission byte array. And ugly leading underscores are just local variables signs :) – Alexander Mikhailove Oct 16 '14 at 13:12
  • I used to get stuck on that stuff. For me the thing "Could not locate the image processing component which is suitable to complete this operation" was simply that the targeted image was either a 0Mb file or corrupted. The code works fine in other cases – L Chougrani Jan 01 '21 at 18:05

1 Answers1

-1
public BitmapImage ToImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
    var image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad; // here
    image.StreamSource = ms;
    image.EndInit();
    return image;
    }
}

Have you tried this?

RenDishen
  • 928
  • 1
  • 10
  • 30