赞
踩
using System.Collections; using UnityEngine; using UnityEngine.UI; using System; using UnityEngine.Networking; using System.IO; public class UploadImage : MonoBehaviour { public Image img; public void UpLoad() { StartCoroutine(UpLoadTexture()); } IEnumerator UpLoadTexture() { yield return new WaitForSeconds(0.5f); byte[] bytes = File.ReadAllBytes(Application.dataPath + "/StreamingAssets/" + "photo.png"); WWWForm form = new WWWForm(); //string id = "Photo_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"); //form.AddField("id", id);//文件名这个参数是给服务器处理的,服务器不同,参数数量和类型也将不同 form.AddBinaryData("file", bytes, "photo.png"); using (UnityWebRequest www = UnityWebRequest.Post("XXX", form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log("上传失败:" + www.error); } else { string text = www.downloadHandler.text; Debug.Log("服务器返回值" + text);//正确打印服务器返回值 Debug.Log("上传成功!"); StartCoroutine(LoadTexture(text, img)); } } } Texture2D texture2D; IEnumerator LoadTexture(string url, Image image) { print(url); using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url)) { yield return uwr.SendWebRequest(); if (uwr.isNetworkError || uwr.isHttpError) { Debug.Log("图片加载失败" + uwr.error); } else { // Get downloaded asset bundle texture2D = DownloadHandlerTexture.GetContent(uwr); print("图片获取成功!"); Sprite temp = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero); image.sprite = temp; } } } }
/// <summary> /// StreamingAssets加载图片资源 /// </summary> /// <param name="path">文件夹路径</param> /// <returns></returns> public Texture2D GetTexture(string path) { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, (int)fileStream.Length); fileStream.Close(); fileStream.Dispose(); fileStream = null; int width = 300; int height = 372; Texture2D texture = new Texture2D(width, height); texture.LoadImage(bytes); //Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); //image.sprite = sprite; return texture; }
将Texture2d转换为Sprite
private Sprite TextureToSprite(Texture2D tex)
{
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
return sprite;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。