简体   繁体   中英

How do I populate a list of Images from a directory?

trying to load in a bunch of images into a list from a directory...my code is below.

        string directory = @".\card_images\";
        List<Image> HandCards = new List<Image>();
foreach (string myFile in 
         Directory.GetFiles(directory,"*.png",SearchOption.AllDirectories))
        {
            HandCards.Add(myFile);
        }

This of course doesn't work because a string can't be converted to an Image, on the other hand if I try to make myFile into Image then Directory.GetFiles doesn't work either, any help would be appreciated. Thanks!

A cute one liner:

var handCards = Directory.GetFiles(directory, "*.png", 
                                   SearchOption.AllDirectories)
                         .Select(Image.FromFile).ToList();
string directory = @".\card_images\";
List<Image> HandCards = new List<Image>();
foreach (string myFile in
          Directory.GetFiles(directory, "*.png", SearchOption.AllDirectories))
{
    Image image = new Image();
    BitmapImage source = new BitmapImage();
    source.BeginInit();
    source.UriSource = new Uri(myFile, UriKind.Relative);
    source.EndInit();
    image.Source = source;

    HandCards.Add(image);
}

Try using Image.FromFile

Eg:

string directory = @".\card_images\";
List<Image> HandCards = new List<Image>();
foreach (string myFile in Directory.GetFiles(directory,"*.png",SearchOption.AllDirectories))
{
    HandCards.Add(Image.FromFile(myFile));
}

You would just need to bind (read this) the HandCards collection and use an ItemTemplate to template the strings to an Image .

eg

<ItemsControl ItemsSource="{Binding HandCards}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM