图像查看器和高内存使用
本文关键字:内存 高内存 图像 | 更新日期: 2023-09-27 18:16:58
我正在使用。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;
}
问题是显示图像时ram峰值和总体ram使用情况。我用于测试的图像是一张5000x5000的jpeg。FreeImage报告它在内存中占用了70mb的ram,这是正确的。如果我只运行这一部分,我的应用程序大约需要100mb(WPF约为30 mb, image为70 mb):
_rawImage = new FreeImageBitmap(path);
但是当运行完整的代码时,内存峰值约为280mb,这太大了。在生产代码中,我显然可以处理所有未使用的道具,但最初的峰值太多了。我使用IrfanView来浏览图片,同样的图片只占用77mb的内存。
我想要一些解决方案(如果有一个),以摆脱它需要加载和转换成格式的图像wpf图像可以显示的峰值。如果可能的话,可能会进一步减少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。