简体   繁体   English

如何在中显示资源属性图像<img> ?

[英]How do I display a resource property image in <Image>?

I'm trying to display an image I have saved as a resource under the properties category.我正在尝试显示我已保存为属性类别下的资源的图像。 This property however returns a byte[] which can't be displayed by <Image> since it can't convert it to ImageSource .然而,此属性返回一个byte[]<Image>无法显示它,因为它无法将其转换为ImageSource The code looks like this:代码如下所示:

public byte[] MyImage = Properties.ImageResources.MyImage

but plugging MyImage into但将MyImage插入

<Image Source="{x:Bind MyImage}"

gives me a conversion error as described above.如上所述给我一个转换错误。

I've already tried converting the image to a bitmap to display this instead, but I got the very same error.我已经尝试将图像转换为 bitmap 来显示它,但我得到了完全相同的错误。 I've read alot about something like我读过很多类似的东西

bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();

but then it tells me it can't resolve any of the BitmapImage Functions -> BeginInit, EndInit, StreamSource and CacheOption.但随后它告诉我它无法解析任何BitmapImage函数 -> BeginInit、EndInit、StreamSource 和 CacheOption。

I've searched far and wide but they all end in this BeginInit() and EndInit() function which do not exist for me.我进行了广泛的搜索,但它们都以这个BeginInit()EndInit() function 结尾,这对我来说不存在。

Do you have a UWP application?您有 UWP 申请吗? In WPF, when Binding is used, type conversion is performed. WPF,使用Binding时,进行了类型转换。 The ImageSource type provides conversion from the Stream, byte[], Uri and string types. ImageSource 类型提供从 Stream、byte[]、Uri 和 string 类型的转换。 You are using x:Bind.您正在使用 x:Bind。 And x:Bind does no type conversion.并且 x:Bind 不进行类型转换。
I'm not sure about UWP, but try replacing x:Bind with Binding.我不确定 UWP,但请尝试将 x:Bind 替换为 Binding。

You can get an ImageSource from an array of bytes like this:您可以像这样从字节数组中获取 ImageSource:

    BitmapImage bitmap = new();
    using (MemoryStream stream = new(imageBytes))
    {
        bitmap.BeginInit();
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.StreamSource = stream;
        bitmap.EndInit();
    }
    bitmap.Freeze();

Also, keep in mind that bindings require properties, not fields.另外,请记住绑定需要属性,而不是字段。

public byte[] MyImage {get;} = Properties.ImageResources.MyImage;

For WinUI it might be like this:对于 WinUI,它可能是这样的:

    var bitmapImage = new BitmapImage();

    using (var stream = new InMemoryRandomAccessStream())
    {
        using (var writer = new DataWriter(stream))
        {
            writer.WriteBytes(bytesArray);
            writer.Store().Wait();
            writer.Flush().Wait();
            writer.DetachStream();
        }

        stream.Seek(0);
        bitmapImage.SetSource(stream);
    }

I took as a basis the code from the topic: Convert byte[] to Windows.UI.Xaml.Media.Imaging.BitmapImage .我以主题中的代码为基础: Convert byte[] to Windows.UI.Xaml.Media.Imaging.BitmapImage
The topic shows an asynchronous solution.该主题显示了一个异步解决方案。 Here I tried to upgrade it to synchronous.这里我尝试将其升级为同步。 I'm not sure if my code is correct because there are many types and methods in WinUI that I don't know about.我不确定我的代码是否正确,因为 WinUI 中有许多我不知道的类型和方法。

Thanks to the help of EldHasp I've found a way to make the images appear.感谢EldHasp 的帮助,我找到了使图像出现的方法。

I have created a data binding converter class that implements the IValueConverter interface:我创建了一个实现IValueConverter接口的数据绑定转换器 class:

public class ByteArrayToBitmapImageConverter : IValueConverter
{
    public object? Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is not byte[])
        {
            return null;
        }

        using var ms = new InMemoryRandomAccessStream();
        using (var writer = new DataWriter(ms.GetOutputStreamAt(0)))
        {
            writer.WriteBytes((byte[])value);
            writer.StoreAsync().GetResults();
        }

        var image = new BitmapImage();
        image.SetSource(ms);
        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}

Or shorter:或者更短:

public object Convert(
    object value, Type targetType, object parameter, string language)
{
    BitmapImage image = null;

    if (value is byte[] buffer)
    {
        using var ms = new MemoryStream(buffer);
        image = new BitmapImage();
        image.SetSource(ms.AsRandomAccessStream());
    }

    return image;
}

It would be used in XAML eg like shown below, when MyImage is a public property of the object in the DataContext of the Grid:它将在 XAML 中使用,如下所示,当MyImage是 object 在 Grid 的 DataContext 中的公共属性时:

<Grid>
    <Grid.Resources>
        <local:ByteArrayToBitmapImageConverter x:Key="ImageConverter"/>
    </Grid.Resources>

    <Image Source="{Binding MyImage, Converter={StaticResource ImageConverter}}"/>
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM