【问题标题】:Get image from resource dll as MemoryStream从资源 dll 中获取图像作为 MemoryStream
【发布时间】:2011-12-13 20:52:12
【问题描述】:

我使用 WPF,我的程序在 DLL 资源文件中有图像。我有这种从磁盘读取图像的有效方法:

Private Function GetImageFromFile(ByVal fileName As String) As BitmapImage
    Dim buffer As Byte() = IO.File.ReadAllBytes(fileName)
    Dim memoryStream As New IO.MemoryStream(buffer)

    Dim bitmap As New BitmapImage()
    bitmap.BeginInit()
    bitmap.StreamSource = memoryStream
    bitmap.EndInit()
    bitmap.Freeze()

    Return bitmap
End Function

现在,我如何以这种 MemoryStream 方式从 DLL 资源中获取图像?

基本问题:如果我简单地使用“bitmap.UriSource = 不管 uri”的方式并像动画一样按顺序加载许多图像,它会建立内存。我尝试使用上述内存流方式,它工作得非常好,但是我将图像存储在一个 dll 中,我不知道如何做到这一点。如果有人知道如何在不建立内存的情况下从托管 dll 读取许多图像,请告诉我。

【问题讨论】:

    标签: wpf vb.net image memorystream


    【解决方案1】:

    我找到了我的问题的答案。我把它放在这里给其他可能需要它的人。有更多方法可以从资源 dll 文件中加载图像。初始化 BitmapImage 并设置 bi.UriSource=uriPath 的最简单方法(路径如下所示)但是当您按顺序加载图像时,例如动画,它似乎需要大量内存。然后您可以使用如下所示的 StreamResourceInfo 并输入 bi.StreamSource = sri.Stream。这也有效,但在记忆方面它具有相同的结果。所以在实践中,我发现以下方式是按顺序加载数百张图像的最快和最节省内存的方式:

    Public Function GetImageFromDLL(ByVal uriPath As String) As BitmapImage
        Dim sri As Windows.Resources.StreamResourceInfo = Application.GetResourceStream(New Uri(uriPath, UriKind.Absolute))
        Dim binReader As New System.IO.BinaryReader(sri.Stream)
        Dim buffer As Byte() = binReader.ReadBytes(sri.Stream.Length)
        Dim memoryStream As New IO.MemoryStream(buffer)
    
        Dim bi As New BitmapImage()
        bi.BeginInit()
        bi.CacheOption = BitmapCacheOption.Default
        bi.CreateOptions = BitmapCreateOptions.None
        bi.StreamSource = memoryStream
        bi.EndInit()
        bi.Freeze()
    
        Return bi
    End Function
    

    uriPath 类似于:"pack://application:,,,/YourDLL;Component/YourImageFile.jpg"

    【讨论】:

    • 很好的答案!我实际上使用它直接加载到位图中以在 WinForms 报告工具中使用。其他人都建议加载到 BitmapImage 并使用编码器保存到 Bitmap 可以查看的流中。然而,这与格式无关。
    猜你喜欢
    • 1970-01-01
    • 2012-04-27
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多