【问题标题】:What is the easiest way to display an image from Byte[]?从 Byte[] 显示图像的最简单方法是什么?
【发布时间】:2016-07-21 00:07:57
【问题描述】:

我有一个包含黑白图像的结构:

public class Img
{
    public int height;
    public int width;
    public byte[] matrix;
}

矩阵中包含的值为0或255。

使用 C# WPF 在组件中显示此图像的最佳方式是什么?

我试过这个:

XAML:

<Image Grid.Row="0"
       Stretch="Uniform"
       Source="{Binding Picture, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>

C#:

public BitmapImage Picture
{
    get
    {
        return _picture;
    }
    private set
    {
        _picture = value;
        OnPropertyChanged("Picture");
    }
}

public void Generate()
{
    Img img = CreateImg();
    Picture = LoadImage(img.width, img.height, img.matrix);
}

private BitmapImage LoadImage(int w, int h, byte[] imageData)
{
    using (MemoryStream memory = new MemoryStream(imageData))
    {
        memory.Position = 0;
        BitmapImage bitmapimage = new BitmapImage();
        bitmapimage.BeginInit();
        bitmapimage.StreamSource = memory;
        bitmapimage.EndInit();
        return bitmapimage;
    }
}

但它不起作用:

“来自 HRESULT 的异常:0x88982F50”

【问题讨论】:

  • 我检查并在项目中为我工作的确切代码
  • 我看过这篇文章,我的LoadImage 就是从这里开始的,但是我有一个例外,想知道由于我的图像是黑白的,是否有更好的方法
  • matrix 真的是一个包含图像的字节数组吗?通过写入文件来检查它并在图像查看器中将其作为原始文件读取。
  • 我已经编辑了你的标题。请参阅Should questions include “tags” in their titles?,其中的共识是“不,他们不应该”。

标签: c# wpf image


【解决方案1】:

BitmapImage.StreamSource 属性只接受包含编码位图缓冲区的流,例如PNG 或 JPEG。

为了从原始像素数据创建BitmapSourceBitmapImage 的基类),您可以使用BitmapSource.Create() 方法。根据每个像素的位数以及 alpha 和颜色通道的顺序,您还必须选择合适的 PixelFormat

假设一个 8 位灰度格式,你会像这样创建一个 BitmapSource:

private BitmapSource LoadImage(int width, int height, byte[] imageData)
{
    var format = PixelFormats.Gray8;
    var stride = (width * format.BitsPerPixel + 7) / 8;

    return BitmapSource.Create(width, height, 96, 96, format, null, imageData, stride);
}

当然,您还必须将属性类型更改为 BitmapSource(无论如何这更灵活,因为您仍然可以分配 BitmapImage)。

public BitmapSource Picture { get; set; }

【讨论】:

    【解决方案2】:

    试试this:

        private static BitmapImage LoadImage(byte[] imageData)
        {
            if (imageData == null || imageData.Length == 0) return null;
            var image = new BitmapImage();
            using (var mem = new MemoryStream(imageData))
            {
                mem.Position = 0;
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = null;
                image.StreamSource = mem;
                image.EndInit();
            }
            image.Freeze();
            return image;
        }
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 2014-01-04
      • 2014-05-16
      • 2011-02-17
      相关资源
      最近更新 更多