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?
c # asp.net-mvc-5 image-resizing
Martin m
source share