簡體   English   中英

從字節數組創建BitMapImage

[英]Create BitMapImage from byte array

如何從字節數組創建bitmapimage對象。 這是我的代碼:

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();
}

運行EndInit()命令時,出現以下異常。

No imaging component suitable to complete this operation was found.

我希望這些行可以創建尺寸為1x10像素的圖像,其中包含兩種顏色。

我究竟做錯了什么? 異常是什么意思?

提前致謝!

創建位圖圖像時,將根據其編碼( BitmapImage和Encoding )從源中加載圖像。 C#支持許多種位圖編碼

您看到的錯誤可能是因為BitmapImage類找不到從字節數組到支持的編碼的合適轉換。 (從編碼中可以看到,許多是4或8的倍數,而10則不是)。

我建議創建一個字節數組,其中包含所需結果的正確編碼內容。 例如, Rbg24格式每個像素將具有三個字節的數據。

我認為您需要使用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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM