wpf - 从字节数组创建 BitmapImage

标签 wpf bitmapimage notsupportedexception

我正在创建一个包含任意值的字节数组,并希望将其转换为 BitmapImage。

    bi = new BitmapImage();
    using (MemoryStream stream = new MemoryStream(data))
    {
      try
      {
        bi.BeginInit();
        bi.CacheOption = BitmapCacheOption.OnLoad;
        bi.StreamSource = stream;
        bi.DecodePixelWidth = width;

        bi.EndInit();

      }
      catch (Exception ex)
      {
        return null;
      }
    }

这段代码一直给我一个 NotSupportedException 。
如何从任何字节数组创建 BitmapSource?

最佳答案

给定一个字节数组,其中每个字节代表一个像素值,您可以创建如下所示的灰度位图。您需要指定位图的宽度和高度,当然必须与缓冲区大小匹配。

byte[] buffer = ... // must be at least 10000 bytes long in this example

var width = 100; // for example
var height = 100; // for example
var dpiX = 96d;
var dpiY = 96d;
var pixelFormat = PixelFormats.Gray8; // grayscale bitmap
var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8; // == 1 in this example
var stride = bytesPerPixel * width; // == width in this example

var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
                                 pixelFormat, null, buffer, stride);

每个字节值也可以代表调色板的索引,在这种情况下,您必须指定 PixelFormats.Indexed8当然也可以传入一个合适的调色板。

关于wpf - 从字节数组创建 BitmapImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15274699/

相关文章:

wpf - 未找到方法 : 'Void Caliburn.Micro.Bootstrapper` 1. .ctor(Boolean)'

wpf - 使用 WPF 时如何消除菜单字体模糊?

c# - 在遍历集合时从 ObservableCollection 中删除项目

c# - 下载文件时出现 NotSupportedException

c# - 已尝试附加或添加不是新实体,可能是从另一个 DataContext 加载的

c# - 重叠投影效果

c# - 如何从 BitmapImage 获取 BitmapSource?

c# - 如何在 WPF TreeView 中添加和显示图像?

c# - 在理解此示例代码方面需要帮助

java.lang.UnsupportedOperationException : Blobs are not cacheable