我得到了一些非常大的建筑图纸,有时22466x3999的深度为24,甚至更大。 我需要能够将这些尺寸调整为较小的版本,并且能够将图像的各部分裁剪为较小的图像。C#裁剪和调整大图像
我一直在使用下面的代码来调整图像,我发现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中。
所以我想知道,如何在不将整个图像加载到内存中的情况下调整图像大小?
这不是一个编程解决方案,但你可以尝试增加*虚拟内存*你的机器的尺寸看看。 – Kurubaran 2015-03-13 08:59:14
你应该使用LockBits来处理这样的图像大小 – Vajura 2015-03-13 08:59:29
@Kurubaran我试图增加内存大小,但这并不奏效,我不认为它是Web项目的正确解决方案。 – 2015-03-13 10:54:04