Search code examples
c#imagesave-imageloading-image

Loading/Saving images misorder


I got a directory full of only PNG images (580 images). I load the images in memory with this function

private List<Bitmap> images = new List<Bitmap>();

foreach (String s in Directory.GetFiles(@"frames\", "*.png"))
     {
        images.Add(new Bitmap(s));
     }

But after loading if I try to save all the images to hdd with this:

System.IO.Directory.CreateDirectory("result");
for (int i = 0; i < images.Count; i++)
   {
      images[i].Save(Application.StartupPath + "\\result\\img" + i + ".png", ImageFormat.Png);
   }

Somes images are saved in the wrong order that they were before loading them to memory.

What might be the problem?


Solution

  • If you need to have file names sorted - you need to do it by hand since order in which GetFiles returns file names is not guaranteed.

    I.e. simply sort by name:

    foreach (String s in Directory.GetFiles(@"frames\", "*.png").OrderBy(t=>t))
    {
     ...
    }