C#裁剪并调整大图像的大小

Mar*_*n M 7 c# image-resizing asp.net-mvc-5

我得到了一些非常大的建筑图纸,有时是22466x3999,深度为24,甚至更大.我需要能够将这些版本调整为较小的版本,并能够将图像的各个部分剪切成较小的图像.

我一直在使用以下代码来调整图像大小,我在这里找到:

       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);
        }
Run Code Online (Sandbox Code Playgroud)

这个代码裁剪图像:

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我尝试调整图像大小时,我得到一个Sytem.OutOfMemoryException,这是因为我无法将完整图像加载到FullsizeImage中.

那么我想知道的是,如何在不将整个图像加载到内存中的情况下调整图像大小?

rdu*_*com 5

有可能OutOfMemoryException不是因为图像的大小,而是因为你没有正确处理所有的一次性类:

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

没有按照他们的意愿处理.你应该using()在它们周围添加一个声明.

如果您只使用一个图像确实遇到此错误,那么您应该考虑将项目切换到x64.22466x3999图片在内存中意味着225Mb,我认为它不应该是x86的问题.(所以先尝试处理你的对象).

最后但同样重要的是,Magick.Net非常有效地调整大型图片的大小/裁剪.