I have a problem with out of memory when I’m trying load a few images into one picturebox.
public void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
string selected = dialog.SelectedPath;
string[] imageFileList = Directory.GetFiles(selected);
int iCtr = 0,zCtr = 0;
foreach(string imageFile in imageFileList)
{
if (Image.FromFile(imageFile) != null)
{
Image.FromFile(imageFile).Dispose();
}
PictureBox eachPictureBox = new PictureBox();
eachPictureBox.Size = new Size(100,100);
// if (iCtr % 8 == 0)
//{
// zCtr++;
// iCtr = 0;
//}
eachPictureBox.Location = new Point(iCtr * 100 + 1, 1);
eachPictureBox.Image = Image.FromFile(imageFile);
iCtr++;
panel1.Controls.Add(eachPictureBox);
}
}`enter code here`
Bad. You’re loading the image from the file, checking to see if the result is null…then loading it again into a new result so that you can dispose it. While the latter portion is silly, it isn’t harmful. The first portion is, however, as the resulting
Imageis never properly disposed of (if/when the GC collects it, the finalizer on theImagetype should dispose of the unmanaged resources, but this is not a wise thing to rely on).Incidentally,
Image.FromFilewill never returnnull. If it cannot read the image, then it will throw anOutOfMemoryException.The code also appears to do nothing, since there’s no
elseblock and nothing meaningful is done in theifblock.My guess is that your
OutOfMemoryExceptionis coming from the fact that one or more of the files in that directory is stored in a corrupted or unsupported image format, or isn’t an image at all.Try replacing the code in your
foreachwith this: