Unity动态加载本地图片

Unity运行时动态加载本地图片

一、Unity运行时加载本地文件夹下所有图片的方法,用于在使用图片前加载完成

//引入命名空间
using System;
using System.IO;

    /// 
    /// 加载图片的Byte[]数组
    /// 
    /// 地址
    public List LoadImage(string filesName)
    {
        List list = new List();
        string tempPath ="E:\"+filesName;  // 图片所在文件夹地址

        List filePaths = new List();
        string imgtype = "*.BMP|*.JPG|*.PNG";
        string[] ImageType = imgtype.Split('|');
        for (int i = 0; i < ImageType.Length; i++)
        {
            //文件夹下所有的图片路径  
            string[] dirs = Directory.GetFiles(tempPath, ImageType[i]);
            for (int j = 0; j < dirs.Length; j++)
            {
                filePaths.Add(dirs[j]);
            }
        }

        for (int i = 0; i < filePaths.Count; i++)
        {
            byte[] bs = getImageByte(filePaths[i]);
            list.Add(bs);
        }
        return list;
    }
    #endregion

    ///   
    /// 根据图片路径返回图片的字节流byte[]  
    ///   
    /// 图片路径  
    /// 返回的字节流  
    private byte[] getImageByte(string imagePath)
    {

        FileStream files = new FileStream(imagePath, FileMode.Open,FileAccess.Read);
        files.Seek(0,SeekOrigin.Begin);
        byte[] imgByte = new byte[files.Length];
        files.BeginRead(imgByte,0,(int)files.Length,CallBack,files);
        return imgByte;
    }

    /// 
    /// 异步加载
    /// 
    /// 
    void CallBack(IAsyncResult ar)
    {
        FileStream fs = ar.AsyncState as FileStream;
        fs.Close();
        fs.Dispose();
    }

用的时候:

List data=new  List();  //临时接收图片数据流
List turList=new List();  //保存图片
data=加载类.LoadImage("测试图片");
foreach (byte[] item in data)
{
   Texture2D tex = new Texture2D(100, 100, TextureFormat.RGBA32, false);  
   tex.LoadImage(item); //建议哪里调用哪里转  还可转精灵
   turList.Add(tex);  
}

二、临时加载一张图片

    public static class ImageLoad {

       		public static Texture2D LoadImageByte(string path){
            FileStream files=new FileStream (PathSet.dataPath+path,FileMode.Open,FileAccess.Read);
            files.Seek(0,SeekOrigin.Begin);
            byte[] imgByte=new byte[files.Length];

            //少量临时加载会 红问号 
            //files.BeginRead(imgByte,0,(int)files.Length,CallBack,files);

            files.Read(imgByte,0,imgByte.Length);
            files.Close();

            Texture2D tx=new Texture2D (512,512);
            tx.LoadImage(imgByte);
            return tx;
        }
       static void CallBack(IAsyncResult ar){
           FileStream fileStream=ar.AsyncState as FileStream;
            fileStream.Close();
            fileStream.Dispose();
       } 
    }

你可能感兴趣的:(Unity个人记录)