[英]C# Graphics.DrawImage() throws out of memory exception when trying to combine multiple images
我正在嘗試將多個圖像組合成一個圖像。 這是我現在的代碼:
public static Bitmap Merge(List<Image> imgs)
{
int outputImageWidth = 0;
int outputImageHeight = 0;
foreach (var img in imgs)
{
if(outputImageWidth < img.Width)
{
outputImageWidth = img.Width;
}
outputImageHeight += img.Height;
}
outputImageHeight += 1;
using (Bitmap outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
foreach (var img in imgs)
{
Graphics graphics = Graphics.FromImage(outputImage);
graphics.DrawImage(img, new Rectangle(new Point(0, outputImage.Height + 1), img.Size), new Rectangle(new Point(), img.Size), GraphicsUnit.Pixel);
graphics.Dispose();
graphics = null;
img.Dispose();
}
foreach (var img in imgs)
{
img.Dispose();
}
GC.Collect();
return (Bitmap)outputImage.Clone();
}
}
在調試時,我想通了,然后每當我調用graphics.DrawImage(...)
大約 100-300mb 的 memory 被分配。 我希望每當我處理 object 時它就會得到解放,但是每次迭代時,該過程都會分配更多的 memory,直到我從 memory 頁面中取出大約 32 位之后(位處理)。 有任何想法嗎?
試試這個
public static Bitmap Merge(List<Image> imgs)
{
...
var outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb));
using (var graphics = Graphics.FromImage(outputImage))
{
foreach (var img in imgs)
{
using (img)
graphics.DrawImage(img, new Rectangle(new Point(0, outputImage.Height + 1), img.Size), new Rectangle(new Point(), img.Size), GraphicsUnit.Pixel);
}
return outputImage;
}
}
這個
using
允許始終調用Dispose
的塊的功能,即使在通過過程中拋出異常也是如此Graphics
當然,一旦完成,您將不得不在此方法之外處理生成的 bitmap。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.