2012-02-20 87 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);