c# - 图像查看器和高内存使用率

标签 c# wpf image

我正在使用 .NET 的 FreeImage 包装器在 WPF 中制作一个简单的图像查看器 (http://freeimage.sourceforge.net/)

这是代码

    public static void OpenImage(string path)
    {
        _rawImage = new FreeImageBitmap(path);
        BitmapSource bs = Utils.BitmapToBitmapSource(_rawImage.ToBitmap());
        mainWindow.imageComponent.Source = bs;
        mainWindow.imageComponent.Width = _rawImage.Width;
        mainWindow.imageComponent.Height = _rawImage.Height;

    }

    [System.Runtime.InteropServices.DllImport("gdi32")]
    static extern int DeleteObject(IntPtr o);

    public static BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap source)
    {
        IntPtr ip = source.GetHbitmap();
        BitmapSource bs = null;
        try
        {
            bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
               IntPtr.Zero, Int32Rect.Empty,
               System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        }
        finally
        {
            DeleteObject(ip);
        }

        return bs;
    }

问题是显示图像时内存峰值和整体内存使用情况。我用于测试的图像是 5000x5000 jpeg。 FreeImage 报告它在内存中占用 70mb 的 ram,这是正确的。如果我只运行这部分,我的应用程序大约需要 100mb(WPF 大约 30mb,图像大约 70mb):

_rawImage = new FreeImageBitmap(path);

但是当运行完整代码时,内存峰值达到大约 280mb,这太多了。在生产代码中,我显然可以处理所有未使用的项目,但最初的峰值太多了。我使用 IrfanView 浏览图片,同样的图片只占用 77mb 内存。

我想要一些解决方案(如果有的话)来消除加载并将图像转换为 wpf Image 可以显示的格式所需的峰值。如果可能的话,也许进一步减少 ram 的使用。我处理大图像,如果加载一张图像需要 3 倍的内存,那就太糟糕了。我对 WPF 和这些东西还是比较陌生,所以我可能会遗漏一些东西。

如果在 WPF 中没有可能的解决方案,也许还有别的办法?我愿意接受建议。

我尝试搜索但未能找到任何解决我当前问题的方法。

非常感谢。

最佳答案

这是我的看法:

<Window x:Class="LargeJpeg.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Image x:Name="Image" Stretch="None"/>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var bitmap = new BitmapImage();
        bitmap.BeginInit();

        bitmap.CacheOption = BitmapCacheOption.None;
        bitmap.UriSource = new Uri(@"C:\5x5.jpg", UriKind.Absolute);
        bitmap.DecodePixelWidth = (int)Image.ActualWidth;
        bitmap.EndInit();
        bitmap.Freeze();


        Image.Source = bitmap;
    }
}

平均内存使用量:5000 x 5000 jpeg 上 130 MB。

关于c# - 图像查看器和高内存使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924548/

相关文章:

c# - 在WPF(MVVM)中将数据绑定(bind)到 subview

Android,无法读取我保存到数据文件夹的图像

objective-c - 制作幻灯片

c# - DataGrid 列 XAML

c# - 为什么我需要 2 Console.ReadLine();暂停控制台?

c# - 数据库更改通知到 Windows 服务?

c# - 存储六个单位的最小可能方式

c# - 使用单独的数据库表在 DataGridComboBoxColumn 中设置 ItemSource

html - 禁用某些图像的缓存

c# - ServiceStack.Redis : Configure so that the request and response class/dto is the same class?