来自 base64 和赋值源 - c# 的 WPF 转换文件

本文关键字:WPF 转换 文件 base64 赋值 来自 | 更新日期: 2023-09-27 18:34:22

我从用户点击wpf列表(c#)的json文件中收集。点击调用一个json将Base64中的文件内容传递给我。我会转换它并立即显示它,而无需将其写入用户的 hard 上.

并且'可以转换它并将其留在ram上然后可以立即看到,以及将其分配给对象的源imageViewer?

谢谢

   <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="40"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock FontFamily="{StaticResource Lato Thin}" Margin="10,0,0,0" Foreground="#007AFF" Text="{x:Static res:strings.indietroPage}" MouseDown="GoBackFrame_MouseDown" FontSize="20" Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Center"/>
            <Image Grid.Row="1" Source="{Binding uriImageSource}" Name="imageViewer"></Image>
        </Grid>

首先我先保存到磁盘,然后可视化,但我需要它没有保存到磁盘,并且您立即收到源

File.WriteAllBytes(System.IO.Path.GetTempPath() + attachmentDownload.Name + "." + attachmentDownload.Extension, Convert.FromBase64String(attachmentDownload.B64Content));

我试过这个

fileSourceBytes = Convert.FromBase64String(attachmentDownload.B64Content);
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.StreamSource = new MemoryStream(fileSourceBytes);
                    bi.EndInit();
                    imageViewer.Source = bi;

但收到错误:

对象引用未设置为对象的实例。

来自 base64 和赋值源 - c# 的 WPF 转换文件

解决方案:代码隐藏

public Byte[] fileSourceBytes { get; set; }    
fileSourceBytes = Convert.FromBase64String(attachmentDownload.B64Content);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = new MemoryStream(fileSourceBytes);
bi.EndInit();
uriImageSource = bi;

XAML:

<Image Grid.Row="1" Source="{Binding uriImageSource}" Name="imageViewer"></Image>

也许最好的解决方案是将BitmapImage绑定到 ImageViewer's Source 属性。

视图模型:

BitmapImage _imageViewerSource;
public BitmapImage ImageViewerSource {
    get { return _imageViewerSource; }
    private set
    { 
        _imageViewerSource = value;
        OnPropertyChanged("ImageViewerSource"); // or OnPropertyChanged(nameof(ImageViewerSource)); if you are using VS2015+
    }
}

Xaml:

<Image Source="{Binding ImageViewerSource, Mode=OneWay}"/>

这应该可以解决您的问题

using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
    using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
    {
        writer.WriteBytes(Convert.FromBase64String(base64););
        writer.StoreAsync().GetResults();
    }
    BitmapImage image = new BitmapImage();
    image.SetSource(stream);
}