An ASP.NET application on my server starts throwing GDI+ exception after running for several days. After I restart the server, all works fine for a couple of days and then suddenly this exception occurs again. After the first time it occurs, it occurs every time I try to save a PNG image, until I restart again.
When I try to save the image in JPEG, it works fine.
When I run this code from my project, it fails:
var path = @"C:\Project\images\logo.png";
var image = Image.FromFile(path);
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png); // Fails here on GDI+ exception.
//image.Save(ms, ImageFormat.Jpeg); // JPEG works somehow
}
Again: When I restart remote desktop and run this code, it works for a couple of days and at some moment suddenly starts to fail over and over.
I tried:
To make a console application with the same code and run it in the RDP where the project is. It worked fine!
Lots of different variations of codes that were suggested in more then 10 articles I read on this topic.
GCI.Collect() – no help.
Checked all the folders that has write permissions (maybe there is something with the IIS?).
More.
I think that it should be some configuration that suddenly changes due to something and I can’t understand what can it be.
After I restart the server all works fine for a couple of days and then suddenly this exception occurs and after the first time it occurs it will occur everytime I try to save the PNG image, until I will restart again.
Sounds like a memory leak to me. What .NET version is this compiled to? What server OS this running on?
You can start by enclosing your image in a using block:
var path = @"C:\Project\images\logo.png";
using (Image image = Image.FromFile(path))
{
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png);
}
}
This link I believe is relevant to your case.
It throw GDI+ error because one of your object not disposed, so better dispose used object.
If you are getting that error , then I can say that your application doesn't have a write permission on some directory.
GDI+ limits the height of an image to 65534
Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.
var path = @"C:\Project\images\logo.png";
using (Image image = Image.FromFile(path))
{
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png); //fails here on GDI+ exception.
//image.Save(ms, ImageFormat.Jpeg); //Jpeg Works somehow
}
}
The FromFile method locks the file, so use the Image.FromStream() method for reading the image:
byte[] bytes = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png); //fails here on GDI+ exception.
//image.Save(ms, ImageFormat.Jpeg); //Jpeg Works somehow
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With