Exclude memory in System.Drawing.Image.FromStream ()

I have an application that processes and resizes images and from time to time during long iterations. I get an OutOfMemoryException.

I save my images in the database as a stream 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 something 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 looked at this similar thread, but none of the answers seem to be applicable in my case.

One answer suggests using Image.FromStream (), but that is what I do anyway.

, . , , , , , . , .

, ( , ).

Hangfire. ?

+4
3

, OOM, , . , , . , - , , , . :

   foreach (var car in cars)

, . , , , (photos.Binary). , , , , , , . - , . , , 64- .

   using (var memoryStream = new MemoryStream(photo.Binary))

, , , . LOH , MemoryStream , . , , . , , , , . , . , , Capacity .

    Graphics.FromImage(bitmap).DrawImage(image, 0, 0, newWidth, newHeight);

Graphics . using, .


, , , . , , 64- . , .

+6

( ), :

var resized = image.GetThumbnailImage(newWidth, newHeight,() => false, IntPtr.Zero);
resized.Save(directory + filePath);
0

. , Image Object , USING.

 IEnumerable<Control> mcontrols = this.panel1.Controls.Cast<Control>().Where(n => n.GetType() == typeof(PreviewImage));
        // for unclear reason after the dispose needs many times to clear everything;
        while (mcontrols.Count() != 0)
        {
            foreach (PreviewImage pi in mcontrols)
            {
                pi.Dispose();
            }
            mcontrols = this.panel1.Controls.Cast<Control>().Where(n => n.GetType() == typeof(PreviewImage));
            if (mcontrols == null) {
                break;
            }

        }

1 . , , .

0

All Articles