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!
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.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.