在unity里面创建StreamingAssets文件夹,
参数是路径,下面是图片的尺寸
方式一
private Sprite LoadImage(string path)
{
Texture2D texture = new Texture2D(701, 395);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
fs.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
texture.LoadImage(bytes);
}
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
还有一种方式
方式二
获取文件夹下所有图片
// 储存获取到的图片
List<Texture2D> allTex2d = new List<Texture2D>();
/// <summary>
/// 读取StremingAssets文件夹指定的文件夹目录下的所有图片进行加载
/// </summary>
/// <param name="path"> StremingAssets文件夹下的文件夹名字 </param>
void Load(string path)
{
List<string> filePaths = new List<string>();
string[] dirs = null;
string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
string[] ImageType = imgtype.Split('|');
for (int i = 0; i < ImageType.Length; i++)
{
//获取Application.dataPath文件夹下所有的图片路径
dirs = Directory.GetFiles((Application.streamingAssetsPath+"/" + path), ImageType[i]);
for (int j = 0; j < dirs.Length; j++)
{
filePaths.Add(dirs[j]);
}
}
Debug.Log("图片数量:" + dirs.Length);
for (int i = 0; i < filePaths.Count; i++)
{
Texture2D tx = new Texture2D(100, 100);
tx.LoadImage(Tools.GetImageByte(filePaths[i]));
///获取图片名字,并去除.png 后缀
tx.name = filePaths[i].Substring(filePaths[i].LastIndexOf(@"\") + 1, filePaths[i].LastIndexOf('.')-filePaths[i].LastIndexOf('\\')-1);
allTex2d.Add(tx);
Debug.Log("Texture2D Name:" + tx.name);
}
}
/// <summary>
/// 根据图片路径返回图片的字节流byte[]
/// </summary>
/// <param name="imagePath">图片路径</param>
/// <returns>返回的字节流</returns>
public 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;
}
欢迎加入游戏开发交流群C+\C# 636926481