使用UnityWebRequest获取网络图片并保存

​
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class NewBehaviourScript : MonoBehaviour
{
    string downloadurl = @"https://lmg.jj20.com/up/allimg/1114/010421142927/210104142927-12-1200.jpg";
    string savepath =null;
    FileInfo file;
    void Start()
    {
        savepath = Application.dataPath + "/666.jpg";
        file = new FileInfo(savepath);

        if (!file.Exists)
            StartCoroutine(DownLoad());
        else
            Debug.LogError("已经存在");
    }
    IEnumerator DownLoad()
    {
        UnityWebRequest request = UnityWebRequest.Get(downloadurl);
        yield return request.SendWebRequest();
        if (request.isDone)
        {
            if (request.isHttpError || request.isNetworkError)
                Debug.Log(request.error);
            else
            {
                Debug.Log(request.downloadHandler.text);
                byte[] bytes = request.downloadHandler.data;
                CreatFile(bytes);
            }
        }
    }
    void CreatFile(byte[] bytes)
    {
        Stream stream;
        stream = file.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }
}

​

猜你喜欢

转载自blog.csdn.net/LuffyZ/article/details/127922075