WWW實現圖片資源顯示以及儲存和本地載入
阿新 • • 發佈:2018-11-05
WWW實現圖片資源顯示以及儲存和本地載入
using UnityEngine; using System.Collections; using System.IO; using UnityEditor; enum GetPicType { DownLoad = 0, LocalLoad, } public class Picture : MonoBehaviour { //這裡是本地的ip地址 string url = "http://127.0.0.1:80000/1.jpg"; /// <summary> /// 網路下載的圖片 /// </summary> private Texture2D img = null; /// <summary> /// 本地圖片 /// </summary> private Texture2D img2 = null; private bool downloadOK = false; void OnGUI() { if (this.img != null) GUI.DrawTexture(new Rect(0, 0, 200, 300), this.img); if (this.img2 != null) GUI.DrawTexture(new Rect(320, 0, 200, 300), this.img2); if (GUI.Button(new Rect(210, 0, 100, 20), "顯示網路圖片")) { StartCoroutine(this.DownLoadTexture(this.url, GetPicType.DownLoad)); } if (GUI.Button(new Rect(210, 50, 100, 20), "顯示本地圖片")) { if (this.downloadOK) { StartCoroutine(DownLoadTexture("file://" + Application.streamingAssetsPath + "/1.png", GetPicType.LocalLoad)); } else { Debug.LogError("沒有下載完畢"); } } } IEnumerator DownLoadTexture(string url, GetPicType getType) { WWW www = new WWW(url); Texture2D tempImage; yield return www; if (www.isDone && www.error == null) { switch (getType) { case GetPicType.DownLoad: { this.img = www.texture; tempImage = this.img; Debug.Log(tempImage.width + " " + tempImage.height); break; } case GetPicType.LocalLoad: this.img2 = www.texture; tempImage = this.img; Debug.Log(tempImage.width + " " + tempImage.height); break; default: tempImage = null; break; } if (tempImage != null) { byte[] data = tempImage.EncodeToPNG(); File.WriteAllBytes(Application.streamingAssetsPath + "/1.png", data); this.downloadOK = true; } } } }