I have a very simple WPF app which is used to preview images in any given folder one image at a time. You can think of it as a Windows Image Viewer clone. The app has a PreviewKeyUp event used to load the previous or next image in the folder if the left arrow or right arrow key is pressed.
<Grid>
<Image x:Name="CurrentImage" />
</Grid>
private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Left:
DecreaseIndex();
break;
case Key.Right:
IncreaseIndex();
break;
}
var currentFile = GetCurrentFile();
CurrentImage.Source = new BitmapImage(new Uri(currentFile));
}
The problem I'm trying to solve is that there is a large amount of memory bloat when loading multiple images until garbage collection occurs. You can see this in the screenshot I took of the app's memory usage. It's not uncommon for it to exceed 300 MB before garbage collection occurs.
I tried wrapping the image in a using statement, but that doesn't work because BitmapImage doesn't implement IDisposable.
using (var image = new BitmapImage(new Uri(currentFile)))
{
CurrentImage.Source = image;
}
What can I do to prevent memory bloat when loading multiple images into my app?
When you say preview, you probably don't need the full image size. So besides of calling Freeze, you may also set the BitmapImage's DecodePixelWidth or DecodePixelHeight property.
I would also recommend to load the images directly from a FileStream instead of an Uri. Note that the online doc of the UriCachePolicy says that it is
... a value that represents the caching policy for images that come from an HTTP source.
so it might not work with local file Uris.
To be on the safe side, you could do this:
var image = new BitmapImage();
using (var stream = new FileStream(currentFile, FileMode.Open, FileAccess.Read))
{
image.BeginInit();
image.DecodePixelWidth = 100;
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
image.Freeze();
CurrentImage.Source = image;
Call .Freeze() on the bitmap object, this sets it in to a read-only state and releases some of the handles on it that prevents it from getting GC'ed.
Another thing you can do is you can tell the BitmapImage to bypass caching, the memory you see building up could be from the cache.
CurrentImage.Source = new BitmapImage(new Uri(currentFile),
new RequestCachePolicy(RequestCacheLevel.BypassCache));
Lastly, if there is not a lot of programs running on the computer putting memory pressure on the system .net is allowed to wait as long as it wants for a GC. Doing a GC is slow and lowers performance during the GC, if a GC is not necessary because no one is requesting the ram then it does not do a GC.
Related
I am loading and unloading images in Canvas. I used the below code to load the Image.
Before loading my Image the memory consumption is 14.8MB.
Canvas c = new Canvas();
Image im = new Image();
ImageSource src = new BitmapImage(new Uri(#"E:Capture.png"));
im.Source = src;
im.Height = 800;
im.Width = 800;
c.Children.Add(im);
homegrid.Children.Add(c); //homegrid is my grid's name
The Image displayed correctly and the memory consumption now is 20.8MB. Then I unloaded the Image by the below code:
foreach (UIElement element in homegrid.Children)
{
if (element is Canvas)
{
Canvas page = element as Canvas;
if (page.Children.Count > 0)
{
for (int i = page.Children.Count - 1; i >= 0; i--)
{
if (page.Children[i] is Image)
(page.Children[i] as Image).Source = null;
page.Children.RemoveAt(i);
}
}
page.Children.Clear();
page = null;
}
}
homegrid.Children.RemoveAt(2);
InvalidateVisual();
The Image gets removed after this, but the memory is still 20.8 MB.
Can anyone help me out this?
First of all you should test by explicitly invoking GC.Collect() to collect memory and see that memory releases or not because GC collection is indeterministic. You can't be sure that after your method execution GC runs and reclaim the memory.
So , at end put this code to explicitly force GC to run to check if actually memory is released or not:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
However, there is some known memory leak issues in BitmapImage creation which you can refer here, here and here.
Actually under the covers WPF keeps a strong reference between the static BitmapImage and the Image and hook some events on Bitmap image. So, you should freeze the bitmapImage before assigning to image. WPF doesn't hook events on freezed bitmapImage. Also set CacheOption to avoid any caching memory leak of bitmapImage.
Image im = new Image();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(#"E:Capture.png");
bi.EndInit();
bi.Freeze();
ImageSource src = bi;
im.Source = src;
im.Height = 800;
im.Width = 800;
In .Net there is something called the garbage collector (GC) that is in charge of managing the memory you're using.
When you create an instance of an object, it requires some more memory.
When you remove your ImageSource from the Children collection, you don't actually free any memory, you just say "I don't want to use this instance anymore".
At this point the GC will help you. It'll automatically detect instances that are not used anymore, and will free the associated memory for you.
Do note it's an automatic process and you shouldn't (and you don't want to) take care of the memory management.
You can call GC.Collect(); to force the garbage collector to do its job right now, you'll see the memory will be released. NOTE: GC.Collect(); should be used in debug to detect memory leaks, but 99% of times you shouldn't call it explicitly in production code. GC.Collect(); is an operation that can use a lot of CPU time.
I am using EmguCV 3.1.0.2282 and I found that when I use an image, there are times when it doesn't release its resources and eats up memory until the PC is out of resources and an out of memory exception is thrown.
Here is a test code I did within my application. When the button is clicked, a new local image is instantiated based on an existing bitmap in memory. It will do a manual dispose if the checkbox is checked.
private void button1_Click(object sender, EventArgs e)
{
Image<Bgr, Byte> TempImage = new Image<Bgr, Byte>(CurrentLeftBitmap);
TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));
if (checkBox1.Checked)
{
TempImage.Dispose();
TempImage = null;
}
}
I found each time I click on the button, memory goes down and won't be released without an application restart. Even when I do a manual dispose, memory still goes down. Funny thing is that if I commented out the ThresholdBinary step, it works fine. However, it still requires a manual dispose. I've also tried the USING statement but still the same.
My question is that has anyone encounter something similar? What is the proper way of implementing these image objects?
Yes, doing this will run you out of memory. I managed to drain my 32GB system doing 5000 iterations of your method. The problem is ThresholdBinary return another Image, you are not taking that image so the memory gets allocated but has no way to be disposed of. Change
TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));
To
Image<Bgr, byte> newImage = TempImage.ThresholdBinary(new Bgr(2.2, 3.3, 4.4), new Bgr(100.0, 100.0, 100.0));
Will help.
Because they are locals the GC will eventually get around to cleaning them up. But it is always a good idea to dispose of things. So I added
TempImage.Dispose();
newImage.Dispose();
Running this 5,000 time my memory usage hardly moved.
I have an image control in my WPF application:
<Image x:Name="image" Source="{Binding}"/>
...and I'm trying to figure out which one would be the most efficient way of setting its source from an icon. I am using SystemIcons.WinLogo as my test subject.
First way involves CreateBitmpapSourceFromHIcon:
image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
SystemIcons.WinLogo.Handle, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
The second approach uses BitmapImage and sets its source from the memory stream:
var ms = new MemoryStream();
SystemIcons.WinLogo.ToBitmap().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
var bmpi = new BitmapImage();
bmpi.BeginInit();
bmpi.StreamSource = ms;
bmpi.EndInit();
image.Source = bmpi;
Which one should I use? They both work and I haven't noticed much difference in performance on my system.
Both will serve the same purpose. If you ask me I would go with first approach because that's straight forward and no need to get icon first save in memory stream.
However, if you want to go with second approach make sure you call Freeze() on bitmapImage instance to avoid any memory leaks. Also freezing it will make it thread safe i.e. you can create a bitmapImage in background thread and can still set as Image source on UI thread.
var bmpi = new BitmapImage();
bmpi.BeginInit();
bmpi.StreamSource = ms;
bmpi.EndInit();
bmpi.Freeze(); <-- HERE
image.Source = bmpi;
I have a timer and on every tick I want to take an image file from memory and change the image that is being displayed in the Image with this piece of code
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Render,
new Action(() =>
{
ms.Seek(0, SeekOrigin.Begin);
e.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.None;
bitmapImage.EndInit();
CameraImageBox.BeginInit();
CameraImageBox.Source = bitmapImage;
CameraImageBox.EndInit();
bitmapImage = null;
ms.Flush();
}));
The Image control turns pitch black after a couple of dozen of images and the whole ui turns quite unresponsive. The memory use jumps to a whopping 1gig, I'm assuming the image controls render cache doesn't get released as e.Image is a static resource that gets redrawn every time.
Is there a better way to do this, like rendering the image in a Rectangle or manually releasing the cache?
it is my understanding that you are adding the image many multiple times to the MemoryStream at every single iteration.
this because your ms object exists from outside and is never disposed. If I am understanding what happens correctly:
// go to begin of stream
ms.Seek(0, SeekOrigin.Begin);
// write your bitmap content into the stream
e.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
...
...
...
// flush to write content to the stream
ms.Flush();
now in theory I understand you are overwriting the same bytes all the time, but why don't you dispose the MemoryStream with a using block inside your method and test the results instead of having it open as a global variable?
my code extracts file icons(or even thumbs). however if i have many files it may take a while. I've tried to use background thread to load icons.
Bitmap created from icon extracted form file and stored in list. It seems that for each native bitmap it handle exist only in owner thread (that is in thread where bitmap created).
In UI thread create WPF bitmaps from those native.
So the problem is that i don't know how to use bitmaps created in background thread in UI thread.
-- or --
2b. Create wpf bitmap in background thread and use them in UI thread
But the problem is exactly the same.
You just need to freeze the images after you load them. Frozen objects are read-only and safe to use across threads. For instance :
private void _backgroundWorkerLoadImage_DoWork(object sender, DoWorkEventArgs e)
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = imageUri;
img.EndInit();
img.Freeze();
e.Result = img;
}
void _backgroundWorkerLoadImage_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var img = e.Result as ImageSource;
imageControl.Source = img;
}
If I understand what you are doing correctly, one way to improve performance might be to introduce some intelligence into the process which is reading the file icons.
Consider the situation in which there are lots of .DOC files in a directory and there isn't much point in reading the file icon for all of them.
You would have a cache of file icons which have been read already instead so it wouldn't be necessary to read the file icon for each of the .DOC files. There is a trade off here for holding the images in memory but you should be able to get a happy medium between performance and using too much memory.