0

I'm attempting to index multiple folders of images into multiple lists. Currently, I'm trying to use System.IO's DirectoryInfo and FileInfo to do this, but my lists' types are Texture2D and so it cannot convert them. So how can I add these images to the lists?

Relevant code:

    using UnityEngine.UI;
    using System.IO;

    public List<Texture2D> daytimeImages = new List<Texture2D>();

    private void Start() {
        DirectoryInfo daytimeDirectory = new DirectoryInfo(daytimePath);
        FileInfo[] daytimePictures = nighttimeDirectory.GetFiles();
        foreach (FileInfo file in nighttimePictures)
        {
            daytimeImages.Add(file);
        }
    }
Shadowtail
  • 180
  • 12
  • 2
    Keyur's answer should do it but please add some kind of protection to the code so that only image files(jpg,png...) are loaded. The code in your question will just get every file in that folder. See [this](https://stackoverflow.com/a/42634328/3785314) answer for how to do that. – Programmer Jun 23 '17 at 02:22

1 Answers1

2

From one of the answers here

This function may help you, it converts image from file path to Texture2d using the LoadImage function:

public static Texture2D LoadImage(string filePath) 
{
    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))     //you can skip this since you are only passing files that exist
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData);
    }
    return tex;
}

You can use it as follows (EDITED to add .FullName)

foreach (FileInfo file in nighttimePictures)
{
    daytimeImages.Add(LoadImage(file.FullName));  //edited
}
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41