using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
using UnityEngine.UI;
public class Test : MonoBehaviour {
void Start()
{
print("当前文件路径:" + Application.persistentDataPath);
//下载图片
StartCoroutine(loadasset("http://127.0.0.1/1.jpg"));
}
//写入图片到本地
IEnumerator loadasset(string url)
{
WWW w = new WWW(url);
yield return w;
if (w.isDone)
{
byte[] model = w.bytes;
int length = model.Length;
//写入图片到本地
string[] urls = url.Split('/');
print(urls[urls.Length - 1]);
CreateObjFile(Application.persistentDataPath, urls[urls.Length - 1], model, length);
}
}
void CreateObjFile(string path, string name, byte[] info, int length)
{
//文件流信息
//StreamWriter sw;
Stream sw;
FileInfo t = new FileInfo(path + "//" + name);
if (!t.Exists)
{
//如果此文件不存在则创建
sw = t.Create();
}
else
{
//如果此文件存在则打开
//sw = t.Append();
return;
}
//以行的形式写入信息
//sw.WriteLine(info);
sw.Write(info, 0, length);
//关闭流
sw.Close();
//销毁流
sw.Dispose();
}
//读取图片文件
IEnumerator LoadObjFromLocal(string path, string name)
{
string s = null;
#if UNITY_ANDROID
s = "jar:file://"+path+"/"+name;
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
s = "file://"+path+"/"+name;
#endif
WWW w = new WWW(s);
yield return w;
if (w.isDone)
{
this.GetComponent<Image>().sprite = Sprite.Create(w.texture, new Rect(0, 0, w.texture.width, w.texture.height), new Vector2(0.5f, 0.5f)); ;
}
}
void OnGUI()
{
if (GUILayout.Button("加载图片"))
{
StartCoroutine(LoadObjFromLocal(Application.persistentDataPath, "1.jpg"));
}
}
}
- 本文固定链接: http://www.nihao6.cn/archives/462
- 转载请注明: 虚拟世界 于 Unity3D虚拟世界 发表
捐 赠如果您愿意花10块钱请我喝一杯咖啡的话,请用手机扫描二维码即可通过支付宝或者微信直接向我捐款,在此非常感谢您对虚拟世界的捐赠。