问题描述
我有一个包含黑白图像的结构:
I have a structure containing an image in black and white:
public class Img
{
public int height;
public int width;
public byte[] matrix;
}
矩阵中包含的值为0或255.
The values containing in matrix are 0 or 255.
使用C#WPF在组件中显示此图像的最佳方法是什么?
What is the best way to display this image in a component using 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;
}
}
但它不起作用:
推荐答案
BitmapImage.StreamSource
属性只接受包含编码位图缓冲区的流,例如PNG或JPEG。
The BitmapImage.StreamSource
property only accepts a stream that contains an encoded bitmap buffer, e.g. a PNG or JPEG.
为了创建 BitmapSource
(的基类BitmapImage
)从原始像素数据中,您可以使用 BitmapSource.Create()
方法。根据每个像素的位数以及alpha和颜色通道的顺序,您还必须选择合适的 PixelFormat
。
In order to create a BitmapSource
(the base class of BitmapImage
) from raw pixel data, you may use the BitmapSource.Create()
method. Depending on the number of bits per pixel, and the ordering of the alpha and color channels, you would also have to choose an appropriate PixelFormat
.
假设有8位灰度格式,你可以像这样创建一个BitmapSource:
Assuming an 8-bit grayscale format, you would create a BitmapSource like this:
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
)。
Of course you would also have to change the type of your property to BitmapSource
(which is more flexible anyway, since you can still assign a BitmapImage
).
public BitmapSource Picture { get; set; }
这篇关于从Byte []显示图像的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!