Reputation: 3046
I'm trying to load some 20 images in my WPF
application. Only the first image loads completely. Other images are loading partially. When i used breakpoint to debug i tried to load each image after 2 seconds and that worked well.
Code
Images will be loaded like,
foreach (string path in ImagesCollection)
{
DisplayImage = LoadImage(path);
}
Load image method,
MemoryStream mem;
if (!string.IsNullOrEmpty(path) && (File.Exists(path)))
{
FileInfo ImageFile = new FileInfo(path);
ImageFile.Refresh();
if (mem != null)
{
mem.Dispose();
}
using (var stream = ImageFile.OpenRead())
{
mem = new MemoryStream();
stream.CopyTo(mem);
}
mem.Position = 0;
ImageFrame = BitmapFrame.Create(mem);
}
Screenshot:
I believe Dispose
or a new instance makes the image doesn't load. Kindly help.
Upvotes: 1
Views: 297
Reputation: 6212
The documentation for BitmapFrame.Create
state "The bitmapStream can be closed after the frame is created only when the OnLoad cache option is used. The default OnDemand cache option retains the stream until the frame is needed"
This means you cannot re-use the MemoryStream once you've passed it to the BitmapFrame. This is the source of the error.
For efficiency just pass the FileStream. Load image method
if (!string.IsNullOrEmpty(path) && (File.Exists(path)))
{
var stream = ImageFile.OpenRead())
ImageFrame = BitmapFrame.Create(stream);
}
Upvotes: 1