Unity C# 安卓读取指定文件夹中的所有图片

 先声明List数组,用于存放加载到图片

 public List<Texture2D> m_ImagesList = new List<Texture2D>();//放在材质球上的图片
    public List<Sprite> m_SpritList = new List<Sprite>();//放在画布上的图片
#region 安卓沙盒文件图片读取
    /// <summary>
    /// 读取Application.persistentDataPath文件夹中的所有图片,并转换成sprite格式
    /// </summary>
    public void LoadFileImage()
    {
       
        //获取streamingAssets文件中的所有图片,供测试使用
        //DirectoryInfo direction = new DirectoryInfo(Application.streamingAssetsPath + "/LecturesImage");
        //获取沙盒指定文件中的指定文件夹
        DirectoryInfo direction = new DirectoryInfo(Application.streamingAssetsPath + "/LecturesImage");
        //返回的指定数组 = 返回当前目录的所有文件列表的名字加格式数组 
        FileInfo[] files = direction.GetFiles("*");
        //存储读取图片的名字字符串
        List<string> imageNames = new List<string>();
        for (int i = 0; i < files.Length; i++)
        { 
            //判断图片的格式字符串是否与指定的字符串不匹配。
            if (!files[i].Name.EndsWith(".meta"))
            {
                //Debug.LogFormat("图片{0}的名字:{1}", i, files[i].FullName);
                //添加图片路径和名字字符串到泛型数组
                imageNames.Add(files[i].FullName);
            }
        }
        //记录加载的图片数量
        //int Total = imageNames.Count;
        //Debug.Log("图片数量:" + Total);
        //-----------------到此都只是存储图片的路径和名字------------------------------
        //逐个转换图片数据流转换为图片,并赋值给m_images泛函数
        for (int j = 0; j < imageNames.Count; j++)
        {
            //字节数组             = 打开图片将图片的内容读入一个字节数组,然后关闭该文件。
            byte[] binaryImageData = File.ReadAllBytes(imageNames[j]);
            //实例化一个物体纹理图片类,
            Texture2D imageTex = new Texture2D(Screen.width, Screen.height);
            //将字节流转换成图片
            imageTex.LoadImage(binaryImageData);//放入imageTex数组中
            //存入图片数组中
            m_ImagesList.Add(imageTex);
            //获取图片名字,并去除.png 后缀
            //imageTex.name = imageNames[j].Substring(imageNames[j].LastIndexOf(@"\") + 1, imageNames[j].LastIndexOf('.') - imageNames[j].LastIndexOf('\\') - 1);
            //Debug.Log("图片名字:" + imageTex.name);

            //将Texture2D类型图片转换为Sprite++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //Sprite sprite = Sprite.Create(imageTex, new Rect(0, 0, imageTex.width, imageTex.height), Vector2.zero);
            //放入泛型函数数组
            //m_SpritList.Add(sprite);

        }
        
    }

猜你喜欢

转载自blog.csdn.net/podaosanshiliu/article/details/127734243