【发布时间】:2015-03-13 08:50:39
【问题描述】:
我得到了一些非常大的建筑图纸,有时是 22466x3999,位深为 24,甚至更大。 我需要能够将这些调整为更小的版本,并且能够将图像的部分剪切成更小的图像。
我一直在使用以下代码来调整图像大小,我发现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);
}
这个代码来裁剪图像:
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;
}
}
我的问题是当我尝试调整图像大小时收到 Sytem.OutOfMemoryException,这是因为我无法将完整图像加载到 FullsizeImage。
那么我想知道的是,如何在不将整个图像加载到内存的情况下调整图像大小?
【问题讨论】:
-
这不是编程解决方案,但您可以尝试增加机器的虚拟内存大小并查看。
-
你应该使用 LockBits 来处理这样的图像尺寸
-
@Kurubaran 我尝试增加内存大小,但没有成功,我认为这不是 web 项目的正确解决方案。
标签: c# asp.net-mvc-5 image-resizing