Unity UnityWebRequest从网页加载图片并永久保存在本地

示例:
Unity UnityWebRequest从网页加载图片并永久保存在本地_第1张图片
Unity UnityWebRequest从网页加载图片并永久保存在本地_第2张图片
创建一个Image组件,将以下代码挂载到Image组件上即可;

代码:

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

public class UnityWebRequestTest : MonoBehaviour
{
     
    /// 
    /// 要加载图片的Url
    /// 
    [SerializeField]
    private string spriteUrl = "https://tse2-mm.cn.bing.net/th/id/OIP-C._7u77Dxc_qt8twaYXp4DawHaP4?pid=ImgDet&rs=1";

    /// 
    /// 是否将加载的图片保存在本地
    /// 
    [SerializeField] private bool isSaveLocally = true;

    void Start()
    {
     
        DownLoadSprite(spriteUrl);
    }

    /// 
    /// 加载图片并且永久保存到本地。
    /// 防止忘记使用协程,多写了一个调用协程的方法
    /// 
    /// 要加载的图片链接
    private void DownLoadSprite(string url)
    {
     
        StartCoroutine(LoadSprite(url));
    }

    /// 
    /// 加载图片并且永久保存到本地
    /// 
    /// 要加载的图片链接
    /// 
    IEnumerator LoadSprite(string url)
    {
     
        UnityWebRequest unityWebRequest = new UnityWebRequest(url);
        DownloadHandlerTexture texD1 = new DownloadHandlerTexture(true);
        unityWebRequest.downloadHandler = texD1;
        yield return unityWebRequest.SendWebRequest();
        int width = 1920;
        int high = 1080;
        if (unityWebRequest.result!=UnityWebRequest.Result.ConnectionError)
        {
     
            Texture2D texture2D = new Texture2D(width, high);
            texture2D = texD1.texture;

            if (isSaveLocally)
            {
     
                SaveLocally(texture2D, "菠萝", ".png");
            }

            Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),
                new Vector2(0.5f, 0.5f));

            transform.GetComponent<Image>().sprite = sprite;
            transform.GetComponent<Image>().SetNativeSize();
        }
    }

    /// 
    /// 下载的图片永久保存在本地
    /// 
    /// 
    /// 自定义图片名称
    /// 要保存的图片格式 (。png/。jpg)等
    private void SaveLocally(Texture2D texture2D, string texName, string spriteType)
    {
     
        Byte[] bytes = texture2D.EncodeToPNG();
        File.WriteAllBytes(Application.dataPath + "/" + texName + spriteType, bytes);
    }

    private void OnApplicationQuit()
    {
     
        StopAllCoroutines();
    }
}

你可能感兴趣的:(unity)