gpt4 book ai didi

c#加载大量图片时出现内存不足异常

转载 作者:行者123 更新时间:2023-11-30 23:17:54 25 4
gpt4 key购买 nike

我正在处理一个 Visual Studio c# 项目。我在 powerpoint 加载项中创建了大量按钮,每个按钮都有一个从 powerpoint 演示文稿库中的幻灯片创建的图像。当按钮数量超过 450 时,它总是会因内存不足异常而崩溃。

我已经研究了这个问题并了解到我需要在某处处理一些东西以释放一些内存。不过,我不清楚如何执行此操作。

这是我用来创建图像的代码,每个图像在创建时都会添加到一个按钮中。它在行 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”

如有任何帮助,我们将不胜感激。

编辑:

这是我使用 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);
}

编辑:

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;
}

最佳答案

您为每个图像创建三个实例

  • 创建非索引图像
  • resizeImage (in if (img.Width > maxWidth))
  • resizeImage (in if (img.Height > maxHeight))

您可以在调整大小后处理旧图像,然后将新实例设置为 img 变量,如下所示

var newImg = resizeImage(img, new Size(maxWidth, newHeight));
img.Dispose();
img = newImg;

关于c#加载大量图片时出现内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com