具有基于流的图像的 XamlWriter 和 XamlReader?

XamlWriter and XamlReader with stream based images?

我使用以下代码即时创建图像:

Public Function ToBitmapImage(byteArray As Byte()) As BitmapImage
    Dim image As New BitmapImage()
    Dim stream As New MemoryStream(byteArray)
    image.BeginInit()
    image.StreamSource = stream
    image.EndInit()
    image.Freeze()
    Return image
End Function

然后我尝试使用以下代码克隆包含图像的对象之一:

Public Function Clone(Of T As DependencyObject)(orginal As T) As T
    If (orginal Is Nothing) Then
        Return Nothing
    End If

    Using stream As New MemoryStream()
        XamlWriter.Save(orginal, stream)
        stream.Position = 0
        Return CType(XamlReader.Load(stream), T)
    End Using
End Function

图片序列化为:

...xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation"...
<av:Image ...>
    <av:Image.Source>
        <av:BitmapImage BaseUri="{x:Null}" />
    </av:Image.Source>
</av:Image>

BaseUri="{x:Null}" 导致 Initialization of 'System.Windows.Media.Imaging.BitmapImage' threw an exception. rownumber 1 row position xxx. 有什么方法可以强制它在 BitmapImage 而不是 baseUrl 中序列化数据?

我找到了一个丑陋的解决方案,而不是使用 image.StreamSource = stream 我将它们写入临时文件并将 BaseUriUriSource 设置为文件位置。

这意味着我必须在处理完这些文件后将其删除,所以如果有更好的解决方案我很感兴趣!