C # Crop and resize large images

I had very large drawings of the building, sometimes 22466x3999 with a bit depth of 24 or even more. I need to be able to resize them to smaller versions and be able to cut parts of the image into smaller images.

I used the following code to resize images that I found here :

public static void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider) { System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); if (OnlyResizeIfWider) { if (FullsizeImage.Width <= NewWidth) { NewWidth = FullsizeImage.Width; } } int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width; if (NewHeight > MaxHeight) { NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height; NewHeight = MaxHeight; } System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); FullsizeImage.Dispose(); NewImage.Save(NewFile); } 

And this code crop the images:

 public static MemoryStream CropToStream(string path, int x, int y, int width, int height) { if (string.IsNullOrWhiteSpace(path)) return null; Rectangle fromRectangle = new Rectangle(x, y, width, height); using (Image image = Image.FromFile(path, true)) { Bitmap target = new Bitmap(fromRectangle.Width, fromRectangle.Height); using (Graphics g = Graphics.FromImage(target)) { Rectangle croppedImageDimentions = new Rectangle(0, 0, target.Width, target.Height); g.DrawImage(image, croppedImageDimentions, fromRectangle, GraphicsUnit.Pixel); } MemoryStream stream = new MemoryStream(); target.Save(stream, image.RawFormat); stream.Position = 0; return stream; } } 

My problem is that I get a Sytem.OutOfMemoryException when trying to resize the image, which is because I cannot load the full image in FullsizeImage.

So, what would I like to know how to resize an image without loading the entire image into memory?

+7
c # asp.net-mvc-5 image-resizing
source share
2 answers

It is likely that OutOfMemoryException not due to the size of the images, but because you did not select all classes of disposable things correctly:

  • Bitmap target
  • MemoryStream stream
  • System.Drawing.Image NewImage

not arranged as they should. You must add the using() statement around you.

If you really encounter this error with only one image, you should consider switching your project to x64. Image 22466x3999 means 225 MB in memory, I think this should not be a problem for x86. (so try to destroy objects first).

Last but not least, Magick.Net is very effective at resizing / cropping large images.

+5
source share

You can also force .Net to read the image directly from disk and stop caching memory.

Using

sourceBitmap = (Bitmap)Image.FromStream(sourceFileStream, false, false);

Instead

...System.Drawing.Image.FromFile(OriginalFile);

see fooobar.com/questions/787125 / ...

+1
source share

All Articles