Visual StudioのC#プロジェクトで作業しています。私はパワーポイントアドインに多数のボタンを作成しています。これらのボタンのそれぞれは、パワーポイントプレゼンテーションのライブラリからのスライドから作成されたイメージを持っています。ボタンの数が450を超えると、メモリ不足の例外が発生しても常にクラッシュします。c#大量の画像を読み込む際にメモリ不足の例外が発生する
私は問題を調査し、メモリを解放するために何かを処分する必要があることを理解しています。私はこれを行う方法については明確ではない。
これはイメージを作成するために使用しているコードです。各イメージは作成時にボタンに追加されます。これは、行canvas.DrawImageUnscaled(sourceImage、0、0)でクラッシュします。
public static Image CreateNonIndexedImage(string path)
{
using (var sourceImage = Image.FromFile(path))
{
var targetImage = new Bitmap(sourceImage.Width, sourceImage.Height,
PixelFormat.Format32bppArgb);
using (var canvas = Graphics.FromImage(targetImage))
{
canvas.DrawImageUnscaled(sourceImage, 0, 0);
}
return targetImage;
}
}
スロー例外:System.Drawing.dll
の 'System.OutOfMemoryExceptionに' 任意の助けいただければ幸いです。
EDIT:
ここで私はCreateNonIndexedImageを使用するコード、画像は、ボタンにリサイズし、追加されています。
for (int i = 0; i < numThumbs; i++)
{
Image img = CreateNonIndexedImage(ThumbsPath + thumbsList[i].Name);
int newHeight = maxHeight;
int newWidth = maxWidth;
if (img.Width > maxWidth)
{
float ratio = (float)img.Width/maxWidth;
float h = img.Height/ratio;
newHeight = (int)h;
img = resizeImage(img, new Size(maxWidth, newHeight));
}
if (img.Height > maxHeight)
{
float ratio = (float)img.Height/maxHeight;
float w = img.Width/ratio;
newWidth = (int)w;
img = resizeImage(img, new Size(newWidth, newHeight));
}
int bW = (img.Width + 20) > minWidth ? img.Width + 20 : minWidth;
//CREATE BUTTON FOR SLIDE
Button b = new Button();
b.AccessibleName = thumbsList[i].Name;
b.Text = slideTitle;
b.TextAlign = ContentAlignment.BottomCenter;
b.Image = img;
b.Width = bW;
b.Height = img.Height + 40;
b.ImageAlign = ContentAlignment.TopCenter;
b.BackColor = Color.AliceBlue;
b.Click += SlideButton_Click;
flowLayoutPanel1.Controls.Add(b);
}
EDIT:resizeImageため
ソースコード:
private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width/(float)sourceWidth);
nPercentH = ((float)size.Height/(float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
'Bitmap'オブジェクトは、' IDisposable'あります。それらも処分していますか? – Enigmativity
同じイメージを2つ作成するのはなぜですか? 1つだけを使用してください。 –
アレクサンダー、私は2つの同一の画像を作成しません、すべての画像が異なります。 – kwibbler