0

How do I create a bitmapimage object from a byte array. Here's my code:

System.Windows.Media.Imaging.BitmapImage image = new 
System.Windows.Media.Imaging.BitmapImage();
byte[] data = new byte[10] { 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 };
using (var ms = new System.IO.MemoryStream(data))
{
    image.BeginInit();
    image.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
    image.StreamSource = ms;
    image.EndInit();
}

When running the EndInit() command, I got the following exception.

No imaging component suitable to complete this operation was found.

I expected that these lines should create an image of dimension 1x10 pixels, containing two colors.

What am I doing wrong? What does the exception mean?

Thanks in advance!

random
  • 487
  • 1
  • 9
  • 19
  • 4
    You have invented your own image format; .NET has no encoder present to decode this format into a bitmap. An image format generally starts with a "magic number" indicating the file format, followed by some metadata about the image, for example its dimensions. Since your array is one-dimensional, how would the encoder know that this is a 10x1 image, as opposed to a 5x2 one? So what I guess you want to do is to initialize a BitmapImage with raw pixel data. See for example https://stackoverflow.com/questions/1176910/finding-specific-pixel-colors-of-a-bitmapimage/1177433. – CodeCaster Sep 09 '19 at 12:06
  • Your source is 8 bits per pixel. Nowhere do you indicate that you only want to use 2 of the 256 possible values. – stark Sep 09 '19 at 12:12
  • 1
    An image file has a text header which you are missing. If you open any binary image with notepad you will see the ascii header in the file. The video card uses the header to determine the image format and you are missing the format. – jdweng Sep 09 '19 at 13:09

2 Answers2

0

When creating a bitmap image the image is loaded from your source based upon its encoding (BitmapImage and Encoding). There are many, many different encodings for bitmaps that are supported by C#.

Likely the error you are seeing is because the BitmapImage class is not finding a suitable translation from your byte array to a supported encoding. (As you can see from the encodings, many are multiples of 4 or 8, which 10 is not).

I would suggest creating a byte array that contains the correct encoding content for your desired outcome. For example the Rbg24 format would have three bytes worth of data per every pixel.

Udo
  • 76
  • 1
  • 3
0

I think you need to use SetPixel()

byte[] data = new byte[10] { 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 };
Bitmap bmp = new Bitmap(1, 10);
for (int i = 0; i < data.Length; i++)
{
  bmp.SetPixel(0, i, data[i] == 1 ? Color.Black : Color.White);
}
bmp.Save("file_path");
ysk
  • 1
  • 2