C
C#2y ago
Denis

❔ Image.FromStream() - OutOfMemoryException

public virtual Image[] GetPreviews(string path)
{
Image ImageFromSetting(string imageSetting)
{
if (imageSetting is null)
return null;

var mstr = new MemoryStream(Convert.FromBase64String(imageSetting));
return Image.FromStream(mstr);
}

return InterfaceClient.GetPreviewsAsync(path, Tuple.Create(ApplicationGuid, ApplicationKey))
.Select(ImageFromSetting)
.Where(image => image != null)
.ToArray();
}
public virtual Image[] GetPreviews(string path)
{
Image ImageFromSetting(string imageSetting)
{
if (imageSetting is null)
return null;

var mstr = new MemoryStream(Convert.FromBase64String(imageSetting));
return Image.FromStream(mstr);
}

return InterfaceClient.GetPreviewsAsync(path, Tuple.Create(ApplicationGuid, ApplicationKey))
.Select(ImageFromSetting)
.Where(image => image != null)
.ToArray();
}
The code above is a an implementation for application plugins that provide document previews, among other things. This method is called around 4000 times, and results in an OutOfMemoryException. As I've discovered, this is due to my misuse of loading images - GDI objects are depleted, thus, resulting in the exception. The question is, how do I dispose of the memory stream and image objects correctly? Doing something like this:
using (var mstr = new MemoryStream(...))
using (var image = Image.FromStream(mstr))
return image;
using (var mstr = new MemoryStream(...))
using (var image = Image.FromStream(mstr))
return image;
... is not a good idea because the returned image object is disposed of upon return, resulting in invalidly provided data.
2 Replies
Denis
DenisOP2y ago
Or is disposing of the mstr (MemoryStream) sufficient?
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server