gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:53:46 26 4
gpt4 key购买 nike

我正在使用 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com