gpt4 book ai didi

c# - 在 C# 中使用非常低的内存显示大量图像?

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:54 25 4
gpt4 key购买 nike

我有一个表单,其中我在 Panel 中动态创建 8 个 PictureBoxes,其中我显示 8 个不同的图像,每个 PictureBox .图片为 50Kb Jpeg。问题是我想让用户也看到 300 张图片,就像 38 个面板,但是每次我LOAD 图像到 PictureBoxes 时我的程序使用 5-7Mb Ram 内存更多。(我从 Windows 的任务管理器中看到它)我怎样才能减少这个增量?我的图片不是那么大,我只想展示预览,我不关心质量。下面是我如何创建 PictureBoxes:

private void buttonAdd_Click(object sender, EventArgs e)
{
Panel pan = new Panel();
PictureBox pic1 = new PictureBox();
pic1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
pic1.Location = new System.Drawing.Point(208, 5);
pic1.Name = "panel" + ctr.Count().ToString() + "pictureBox1";
pic1.Size = new System.Drawing.Size(100, 100);
pic1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
///
/// Same thing other 7 times with differents name and location
///
pan.Location = new System.Drawing.Point(12, 55);
pan.Name = "panel" + ctr.Count().ToString();
pan.Size = new System.Drawing.Size(1088, 129);
pan.TabIndex = 0;
pan.AllowDrop = true;
pan.BackColor = System.Drawing.SystemColors.ControlLight;
pan.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
pan.Controls.Add(pic1);
///
/// Same thing other 7 times
///
this.Controls.Add(pan);
}

下面是我如何填充它们:

void buttonClickEvent(object sender, EventArgs e)
{
string[] files= Directory.GetFiles("mylocalpath");
foreach(string x in files)
{
string imgIndex= x.Remove(0,x.LastIndexOf("_")+1).Remove(1);
PictureBox pic=pictureBox1;
//I get it everytime from imgIndex and sender's parent,
//too much code to show now
pic.ImageLocation = x;
}

}

最佳答案

您可以在很长一段时间内忽略 .NET 中的 IDisposable 接口(interface)。许多 .NET 程序员从不对一次性对象调用 Dispose() 方法,也从不使用 using 语句,他们的程序工作得很好。垃圾收集器让程序继续运行,调用此类的终结器进行清理。

但是 Image 和 Bitmap 类比较特殊。它们是围绕 GDI+(一种非托管 API)的非常薄的托管类包装器。图像可以使用大量 非托管内存来存储像素数据,在大图像上需要数兆字节。将其与不会分配足够的托管对象来触发垃圾收集的程序结合起来,你就会遇到一个胖 pig 问题。

在使用完图像后,您必须处理图像以避免此问题。当您使用 PictureBox.ImageLocation 属性时,这有点困难,因为 PictureBox 类使用工作线程加载图像。它自己不能处理以前的图像,它不知道图像是否可以在其他地方使用。你必须帮助:

    foreach(string x in files)
{
string imgIndex = x.Remove(0,x.LastIndexOf("_")+1).Remove(1);
PictureBox pic = pictureBox1;
//...
if (pic.Image != null) pic.Image.Dispose();
pic.Image = null;
pic.ImageLocation = x;
}

或者改用 Image.FromFile() 方法,这样您就不必查看空图片框。

关于c# - 在 C# 中使用非常低的内存显示大量图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495638/

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