首页 > 解决方案 > 试图在数据网格列中显示数据库中的图像异常“找不到组件”

问题描述

我正在尝试显示数据库中的 varbinary 图像,我正在使用此代码将其转换为 byte[]

电影.cs

if (row["foto"] != DBNull.Value)
                    f.Foto = (byte[])row["foto"];

这就是我选择要发送到数据库的文件的方式

GestaoDeFilmesViewModel.cs

public async static Task<StorageFile> OpenLocalFile(params string[] types)
        {
            var picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            Regex typeReg = new Regex(@"^\.[a-zA-Z0-9]+$");
            foreach (var type in types)
            {
                if (type == "*" || typeReg.IsMatch(type))
                    picker.FileTypeFilter.Add(type);
                else
                    throw new InvalidCastException("A extensão do ficheiro está incorreta");
            }
            var file = await picker.PickSingleFileAsync();
            if (file != null)
                return file;
            else
                return null;
        }

然后像这样发送

GestaoDeFilmesViewModel.cs

public async Task<bool> UpdateFoto(StorageFile file)
        {
            if (file == null)
                return false;
            SelectedFilme.Foto = (await FileIO.ReadBufferAsync(file)).ToArray();
            if(SelectedFilme.Foto == null)
            {
                return false;
            }
            if (SelectedFilme.UpdateFoto() == 1)
            {
                return true;
            }

            return false;
        }

这是我用来将图像从 byte[] 转换为 BitMapImage 的用户控件

FotoControl.xaml

<Page
    x:Class="MyMovies.universal.UserControl.FotoControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyMovies.universal.UserControl"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Image x:Name="Foto"></Image>
    </Grid>
</Page>

这是后面的代码,Source_Changed方法中抛出了一个异常,我会发布一张关于它的图片

FotoControl.xaml.cs

public sealed partial class FotoControl : UserControl
    {
        public FotoControl()
        {
            this.InitializeComponent();
        }
        public byte[] ImageSource
        {
            get { return (byte[])GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(byte[]), typeof(UserControlFolder.FotoControl), new PropertyMetadata(null, new PropertyChangedCallback(Source_Changed)));

        private static async void Source_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null && e.NewValue is byte[] data)
            {
                var instance = d as FotoControl;
                BitmapImage image = new BitmapImage();
                using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(data.AsBuffer());
                    await image.SetSourceAsync(stream);
                }
                instance.Foto.Source = image;
            }
        }
    }

这是我在转换后显示图像的页面

GestaoDeFilmes.xaml

<control:FotoControl ImageSource="{Binding Foto, Mode=TwoWay}"/>

例外 照片不为空

您可以通过调试图像看到 Foto 有内容,不为空。我认为该异常与 Windows 无法从其他人所说的内容中解码图像有关。提前致谢。

标签: c#xamluwp

解决方案


请检查这个。你好像很想念stream.Seek(0)

public async static Task<BitmapImage> ImageFromBytes(Byte[] bytes)
{
    BitmapImage image = new BitmapImage();
    using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
    {
        await stream.WriteAsync(bytes.AsBuffer());
        stream.Seek(0);
        await image.SetSourceAsync(stream);
    }
    return image;
}

推荐阅读