当前位置:   article > 正文

Unity 加载图片的两种方式文件流和UnityWebRequest_unity 文件流读取图片

unity 文件流读取图片
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. using UnityEngine.UI;
  8. public class DemoTest : MonoBehaviour
  9. {
  10. string url = @"E:/simulator/Assets/Images/details/btn_go.png";
  11. [SerializeField] private Image im;
  12. // Start is called before the first frame update
  13. void Start()
  14. {
  15. // Texture2D t = new Texture2D(1,1);
  16. // t.LoadImage(ReadTexture(url));
  17. // Sprite spr = Sprite.Create(t, new Rect(0,0,t.width,t.height), new Vector2(10.0f,10.0f));
  18. // im.sprite = spr;
  19. StartCoroutine(LoadTexture(url));
  20. }
  21. // Update is called once per frame
  22. void Update()
  23. {
  24. }
  25. #region 方法一:通过文件流(System.IO)的形式加载
  26. /// <summary>
  27. /// 文件路径
  28. /// </summary>
  29. /// <param name="path"></param>
  30. /// <returns></returns>
  31. private byte[] ReadTexture(string path){
  32. FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
  33. fileStream.Seek(0, SeekOrigin.Begin);
  34. //创建文件长度buffer
  35. byte[] b = new byte[fileStream.Length];
  36. fileStream.Read(b,0,(int)fileStream.Length);
  37. fileStream.Close();
  38. fileStream.Dispose();
  39. fileStream = null;
  40. return b;
  41. }
  42. #endregion
  43. #region 方法二:通过UnityWebRequest加载
  44. IEnumerator LoadTexture(string url){
  45. var uri = new Uri(Path.Combine(url));
  46. UnityWebRequest uwr = UnityWebRequest.Get(uri);
  47. DownloadHandlerTexture tex = new DownloadHandlerTexture(true);
  48. uwr.downloadHandler = tex;
  49. yield return uwr.SendWebRequest();
  50. if(uwr.isHttpError || uwr.isNetworkError){
  51. Debug.LogError(uwr.error);
  52. }
  53. else{
  54. Texture2D t2d = new Texture2D(1,1);
  55. t2d = tex.texture;
  56. Sprite spr = Sprite.Create(t2d, new Rect(0,0,t2d.width,t2d.height), new Vector2(0.5f,0.5f));
  57. im.sprite = spr;
  58. }
  59. }
  60. #endregion
  61. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/103497
推荐阅读
相关标签
  

闽ICP备14008679号