【问题标题】:WPF C# displaying image at XAMLWPF C# 在 XAML 中显示图像
【发布时间】:2014-02-21 07:27:20
【问题描述】:

有很多关于将byte[] 转换为Bitmap 的示例或源代码,但我不确定如何在我的视图中显示或绑定xaml

我的转换函数如下:

private Bitmap ConvertByteToBitmap(byte[] bmpByte)
{
    ImageConverter converter = new ImageConverter();
    return (Bitmap)converter.ConvertFrom(bmpByte);
}

说我有 10 个用户,用户对象有 photo 变量,它是 byte[] 类型。
现在我想知道如何将转换后的byte[] 绑定到image 标记并在xaml 的网格中显示它们?我是否应该创建另一个变量来存储转换后的图像结果以绑定到xaml

例如:

用户对象
- 姓名:简
- 照片:0x0023347dgas83.....


- 姓名:艾萨克
- 照片:0x1023347ddffeas83.....

通常将Text绑定在textboxlike

<TextBox Text="{Binding [someviewmodel].UserObject.Name}"/>

位图图像的绑定方法呢

【问题讨论】:

  • 在您的视图模型中拥有BitmapImageBitmapSource 类型的属性并与之绑定。
  • @RohitVats:所以我需要转换每个byte[] 并将它们中的每一个存储到它们各自对象的变量中?
  • 如果是这种情况,请不要创建重复副本。而是编写一个转换器,将byte[] 转换为BitmapImage。您可以参考here的转换器代码。

标签: c# wpf image xaml


【解决方案1】:

这行得通:

public class MyItem
{
    private readonly byte[] _image;

    ...

    public byte[] Image { get { return _image; } }

}

然后以 XAML 为例:

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding Image}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ImageSourceConverter 为您完成所有转换

【讨论】:

    【解决方案2】:

    您必须创建一个新变量。 如果你知道图片的尺寸,你可以试试这个:

    Image image;
    BitmapSource bitmapSource = BitmapSource.Create(width, height, dpiWidth, dpiHeight,PixelFormats.Brg32,    null, byteArrayIn, width * PixelFormats.Brg32.BitsPerPixel / 8);
    image.Source = bitmapSource;
    

    BitmapSource.Create()

    你也可以试试这个:

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

    【讨论】:

    • 所以我需要在我的 UserObject 下创建另一个变量来存储转换后的结果?
    • 是的,类型为Image
    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多