io流代码: void LoadByIO() { float time = Time.time; FileStream fs = new File
void LoadByIO() {
float time = Time.time;
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);
fs.Close();
fs.Dispose();
fs = null;
Texture2D t = new Texture2D(1,1);
t.LoadImage(bytes);
img.texture = t;
Debug.Log("IO读取图片用时:" + (Time.time-time));
}
IEnumerator LoadByWWW() {
float time = Time.time;
WWW w = new WWW("file://" + path);
yield return w;
if (string.IsNullOrEmpty(w.error) == false)
{
Debug.Log("error");
}
else {
img1.texture = w.texture;
}
Debug.Log("www读取图片用时:" + (Time.time - time));
}
结果截图:
补充:unity加载文件的方法-用加载图片举例
1、把图片(转换或者不转换为sprite都可)放在Resources里
Texture2D imgTexture = Resources.Load("background_one") as Texture2D;
Sprite sprite = Sprite.Create(imgTexture, new Rect(0, 0, imgTexture.width, imgTexture.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
2、把图片转换成sprite,放在Resources
//Resources.Load加载图片默认的是Texture2D类型,加了typeof(Sprite)后,就是加载为sprite类型
//然后又转换为object,所以要再用as Sprite转换为Sprite,
//如果不加typeof(Sprite),它就是Texture2D转换为object,就不成强制转换为Sprite
Image image = GetComponent<Image>();
image.sprite = Resources.Load("background_one", typeof(Sprite)) as Sprite;
public Sprite play;
public Sprite pause;
Image image = GetComponent<Image>();
image.sprite = play;
image.sprite = pause;
//用www方式读取
string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png";
WWW www = new WWW(path);
Texture2D texture = www.texture;
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
注意:用www加载,最好使用协程,等待图片加载完毕
//创建文件读取流
string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png";
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
byte[] bye = new byte[fileStream.Length];
fileStream.Read(bye, 0, bye.Length);
fileStream.Close();
//创建texture
Texture2D texture2D = new Texture2D(240, 144);
texture2D.LoadImage(bye);
//创建sprite
Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。如有错误或未考虑完全的地方,望不吝赐教。
--结束END--
本文标题: unity 文件流读取图片与www读取图片的区别介绍
本文链接: https://lsjlt.com/news/123424.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0