【问题标题】:Try to load a picture from an array of pictures尝试从图片数组中加载图片
【发布时间】:2017-07-13 11:50:15
【问题描述】:

我正在尝试从我使用 Directory.GetFiles() 创建的图片字符串数组中将图片加载到图片框中。我相信我没有正确设置 picFile。

我已经创建了一个 pictureBox_Click 事件来加载后续图片,但还没有编写该事件处理程序

string fileEntries = "";

private void showButton_Click(object sender, EventArgs e)
{
   // First I want the user to be able to browse to and select a
   // folder that the user wants to view pictures in
   string folderPath = "";
   FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
   if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
   {
       folderPath = folderBrowserDialog1.SelectedPath;
   }

   // Now I want to read all of the files of a given type into a
  // array that from the path provided above
   ProcessDirectory(folderPath);

   // after getting the list of path//filenames I want to load the first image here
   string picFile = fileEntries;
   pictureBox1.Load(picFile);
 }

 public static void ProcessDirectory(string targetDirectoy)
 {
   // Process the list of files found in the directory.
   string[] fileEntries = Directory.GetFiles(targetDirectoy);
  }

  // event handler here that advances to the next picture in the list
  // upon clicking 
}

如果我将字符串数组重定向到控制台,我会看到该目录中的文件列表,但它也有完整路径作为字符串的一部分 - 不确定这是否是问题。

【问题讨论】:

  • 试试pictureBox1.Image = Image.FromFile(picFile);

标签: c# arrays picturebox


【解决方案1】:
string[] fileEntries = ProcessDirectory(folderPath);
if (fileEntries.Length > 0) {
string picFile = fileEntries[0];
pictureBox1.Load(picFile);
}

你已经声明了两次 fileEntries。

public static string[] ProcessDirectory(string targetDirectoy) { 
return Directory.GetFiles(targetDirectoy); 
}

【讨论】:

    【解决方案2】:

    现在我想将给定类型的所有文件读入一个 上面提供的路径中的数组

    因此您必须更改方法ProcessDirectory 的签名以返回包含所有图片文件的字符串affy,您也可以使用搜索模式来获取具有特定扩展名的文件。您可以使用以下签名:

     public static string[]  ProcessDirectory(string targetDirectoy)
     {
         return Directory.GetFiles(targetDirectoy,"*.png");
     }
    

    获得路径列表后//文件名我想在这里加载第一张图片

    因此,您可以调用该方法来获取该特定目录中具有特定扩展名的所有文件。如果数组有任何文件,然后将第一个文件加载到图片框,您可以使用以下代码:

    var pictureFiles = ProcessDirectory(folderPath);
    if (pictureFiles.Length > 0)
    { 
    // process your operations here           
        pictureBox1.Load(pictureFiles[0]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2014-11-07
      • 2011-08-12
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多