I have an application, which processes and re-sizes images and occassionally during long iterations I get OutOfMemoryException.
I store my images in the database as filestream and during processing I need to save them to a temporary physical location.
My models:
[Table("Car")]
public class Car
{
[... some fields ...]
public virtual ICollection<CarPhoto> CarPhotos { get; set; }
}
[Table("CarPhoto")]
public class CarPhoto
{
[... some fields ...]
public Guid Key { get; set; }
[Column(TypeName = "image")]
public byte[] Binary { get; set; }
}
Processing looks roughly like this:
foreach (var car in cars)
{
foreach (var photo in car.CarPhotos)
{
using (var memoryStream = new MemoryStream(photo.Binary))
{
using (var image = Image.FromStream(memoryStream)) // this is where the exception is thrown
{
var ratioX = 600.00 / image.Width;
var newWidth = (int)(image.Width * ratioX);
var newHeight = (int)(image.Height * ratioX);
using (var bitmap = new Bitmap(newWidth, newHeight))
{
Graphics.FromImage(bitmap).DrawImage(image, 0, 0, newWidth, newHeight);
bitmap.Save(directory + filePath);
}
}
}
}
}
I've looked at this similar thread, but none of the answers seems to apply in my case.
One of the answers suggests using Image.FromStream(), but it's what I'm doing anyway.
I'm quite confident all my images are valid. The exception seems to be occurring randomly, most often when it comes to processing larger files, but it happens for smaller ones as well. Sometimes one image will fail, but it will be processed fine the next time.
As far as I can see, I'm disposing of everything correctly (memory stream, image and bitmap).
The job is being trigerred by Hangfire. Could that possibly cause a problem?