unity 获取某个文件夹下的所有图片

来源:互联网 发布:linux修改主机名不重启 编辑:程序博客网 时间:2024/05/17 01:00
hello ,哈哈,第一次写博客略微有点小激动。在博客里写下自己平常的积累还是不错的,决定以后有的新的问题及解决方案都写出来共享一下。前几天有朋友问我unity里怎么从某个文件夹下把所有的图片获取到,并且要能随时显示出来,于是我就写了一个如下简单的例子,如有不妥之处望多指教:[csharp] view plain copy    using UnityEngine;      using System.Collections.Generic;      using System.IO;            public class LoadImage : MonoBehaviour      {          // 储存获取到的图片          List<Texture2D> allTex2d = new List<Texture2D> ();          // Use this for initialization          void Start ()          {              load ();          }                void OnGUI ()          {              if (allTex2d.Count != 0) {                  // 把加载的图片显示出来                  for (int i = 0; i < allTex2d.Count; i++) {                      GUILayout.Button (allTex2d [i]);                  }              }          }                void load ()          {              List<string> filePaths = new List<string> ();              string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";              string[] ImageType = imgtype.Split ('|');              for (int i = 0; i < ImageType.Length; i++) {                  //获取d盘中a文件夹下所有的图片路径                  string[] dirs = Directory.GetFiles (@"d:\\a", ImageType [i]);                  for (int j = 0; j < dirs.Length; j++) {                      filePaths.Add (dirs [j]);                  }              }                            for (int i = 0; i < filePaths.Count; i++) {                  Texture2D tx = new Texture2D (100, 100);                  tx.LoadImage (getImageByte (filePaths [i]));                  allTex2d.Add (tx);              }          }                    /// <summary>          /// 根据图片路径返回图片的字节流byte[]          /// </summary>          /// <param name="imagePath">图片路径</param>          /// <returns>返回的字节流</returns>          private static byte[] getImageByte (string imagePath)          {              FileStream files = new FileStream (imagePath, FileMode.Open);              byte[] imgByte = new byte[files.Length];              files.Read (imgByte, 0, imgByte.Length);              files.Close ();              return imgByte;          }            } 


0 0
原创粉丝点击