我得到了一些非常大的建築圖紙,有時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