capzulu
capzulu

Reputation: 105

C# open multiple images to array

I'm new to C# and I'm trying to open multiple images to an array to later manipulate their pixels, this is my code so far:

private void button1_Click(object sender, EventArgs e)
    {

        openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            Bitmap[] images = new Bitmap(openFileDialog1.FileNames);
            MessageBox.Show(images.Length+" images loaded","",MessageBoxButtons.OK);

        }
    }

I'm getting problems with this line

Bitmap[] images = new Bitmap(openFileDialog1.FileNames);

Can you help me?

Upvotes: 3

Views: 3008

Answers (3)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Or, if you aren't ready for lambdas, something like

openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";       
List<BitMap> images = new List<BitMaps>()
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
  foreach(string fileName in openFileDialog1.FileNames)
  {
     images.Add(new Bitmap(fileName));
  }
} 
MessageBox.Show(String.Format("{0} images loaded",images.Count),"",MessageBoxButtons.OK);

Upvotes: 1

Tarion
Tarion

Reputation: 17134

Bitmap[] images = new Bitmap(openFileDialog1.FileNames);

Bitmap[] images // Is an array of Bitmap

new Bitmap(openFileDialog1.FileNames); // Returns a single (new) Bitmap

I suggest to use a List. And when you are new to C# it is much easier to use foreach than LinQ as Pavel Kymets suggested.

List<Bitmap> images = new List<Bitmap>();
foreach(string file in openFileDialog1.FileNames) {
    images.Add(new Bitmap(file));
}

Upvotes: 3

Pavel Krymets
Pavel Krymets

Reputation: 6293

Use:

 images = openFileDialog1.FileNames.Select(fn=>new Bitmap(fn)).ToArray();

Because openFileDialog1.FileNames is array of strings and Bitmap constructor expects single image file name

Upvotes: 10

Related Questions