【问题标题】:Creating Array of Images with source from a given folder C# Windows Desktop使用给定文件夹中的源创建图像数组 C# Windows 桌面
【发布时间】:2016-01-30 20:51:30
【问题描述】:

大家好,正如标题所说,我正在尝试创建 Image 类型的数组并从文件夹中设置其中图像的来源,因为我在文件夹中有 52 个 png,我不想一个一个地添加它们.. 所以有没有办法做到这一点 ? 这就是我到目前为止得到的:

        void DeckCard()
    {
        Image []Deck=new Image[52];
        for(int i=0;i<=Deck.Length;i++)
        {
            Deck[i] = new Image();
            LayoutRoot.Children.Add(Deck[i]);
            Deck[i].Margin = new Thickness(0, 0, 0, 0);     
            Deck[i].Height = 400;
            Deck[i].Width = 200;

        }
    }

附:文件夹位置是 Assets//Cards/(这里是图片)

【问题讨论】:

标签: c# arrays image windows-8


【解决方案1】:

你必须在目录中找到图像。 看看System.IO.Directory.GetFiles 尤其是SearchPattern 过载。如果它们是 png,它可能看起来像这样:

string[] straImageLocations = System.IO.Directory.GetFiles("DirectoryLocation", "*.png", SearchOption.TopDirectoryOnly);

搜索模式是* -> 通配符匹配任何字符,.png 以“.png”结尾。

然后,您将获得所有文件的位置,您只需将它们加载到图像数组中即可。大致如下:

Image[] Deck = new Image[straImageLocations.Length];
for (int i = 0; i < straImageLocations.Length; i++)
{
    Deck[i] = Image.FromFile(straImageLocations[i]));
}

【讨论】:

    【解决方案2】:

    使用LINQDirectory.GetFiles怎么样:

    Image[] deck = System.IO.Directory.GetFiles("Assets\\Cards\\")
                            .Select(file => System.Drawing.Image.FromFile(file))
                            .ToArray();
    

    编辑


    我从未开发过 Windows 应用商店应用程序,但这是我的尝试(请注意,我没有尝试编译以下代码):

    Image[] cards = ApplicationData.Current.LocalFolder.GetFolderAsync("Assets\\Cards").GetResults()
                           .GetFilesAsync().GetResults()
                           .Select(file =>
    {
           using(IRandomAccessStream fileStream = file.OpenAsync(Windows.Storage.FileAccessMode.Read).GetResults())
           {
               Image image = new Image();
               BitmapImage source = new BitmapImage();
               source.SetSourceAsync(fileStream).GetResults();
               image.Source = source;
    
               // Modify Image properties here...
               // image.Margin = new Thicknes(0, 0, 0, 0);
               // ....
    
               // You can also do LayoutRoot.Children.Add(image);
    
               return image;
           }
    }).ToArray();
    

    呸,太狠了!

    当然,这段代码可以使用async/await很好地重构。

    【讨论】:

    • 请注意,如果此目录中有任何其他不是图像的文件,这可能会引发异常
    • 您好,我似乎无法使用“目录”和 .FromFile 我已经加载了 System.IO 库,但它不会工作
    • @Assim 你加了using System.IO吗?
    • @MatiasCicero 或完全限定名称,如果 OP 有冲突的类,即System.IO.Directory.GetFiles
    • @TheLethalCoder 感谢您的提示。更改了我的答案并添加了相应的命名空间
    【解决方案3】:

    看看它是关于枚举给定目录中的文件的发言:Enumerate Files

    这比 GetFiles 更有效,因为您必须等到 GetFiles 返回所有文件名才能开始使用它。 Enumerate 允许您在此之前开始。

    Enumerate Vs GetFiles

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 2016-06-28
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多