2012-02-20 30 views
3

我是新的C#和我試圖打開多個圖片到一個數組以後操縱他們的像素,這是我到目前爲止的代碼:C#打開多個圖像陣列

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

     } 
    } 

我這條線遇到問題

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

你能幫我嗎?

回答

10

用途:

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

因爲openFileDialog1.FileNames是一個字符串數組和位圖構造函數需要一個圖像文件名

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

Bitmap[] images // Is an array of Bitmap 

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

我建議使用一個列表。而當你剛接觸C#時,使用foreach比使用LinQ更容易,正如Pavel Kymets所建議的那樣。

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

或者,如果你還沒有準備好lambda表達式,像

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