首页 > 解决方案 > 下载图像并保存到设备

问题描述

我在这里遇到了 UnityWebRequest 的一些问题。我尝试下载并保存 jpeg,但似乎下载成功但没有保存,也没有显示来自“saveToFile”功能的日志。

我做错了什么吗?

这是我的代码。

public string folderPath;

void Start()
{
       folderPath = Application.persistentDataPath + "/" + FileFolderName;
}

IEnumerator DownloadingImage(Uri url2)
{
    Debug.Log("Start Downloading Images");

    using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
    {
        // uwr2.downloadHandler = new DownloadHandlerBuffer();
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log(uwr.error);
        }
        else
        {
             Debug.Log("Success");
             Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
             byte[] results = uwr.downloadHandler.data;
             saveImage(folderPath, results);
        }
    }
}

void saveImage(string path, byte[] imageBytes)
{
    //Create Directory if it does not exist
    if (!Directory.Exists(Path.GetDirectoryName(path)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(path));
        Debug.Log("Creating now");
    }
    else
    {
        Debug.Log(path + " does exist");
    }

    try
    {
        File.WriteAllBytes(path, imageBytes);
        Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
    }
    catch (Exception e)
    {
        Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
        Debug.LogWarning("Error: " + e.Message);
    }
}

标签: unity3dunitywebrequest

解决方案


  • 您的文件名错误,因此请提供带有扩展名的文件名,
  • 如果你不提供扩展名,'Directory.Exists' 不知道是文件还是目录。
  • 或者您可以分隔参数,例如 rootDirPath 和文件名。
IEnumerator DownloadingImage(Uri url2)
{
    Debug.Log("Start Downloading Images");

    using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
    {
        // uwr2.downloadHandler = new DownloadHandlerBuffer();
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log(uwr.error);
        }
        else
        {
                Debug.Log("Success");
                Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
                byte[] results = uwr.downloadHandler.data;
                string filename = gameObject.name+".dat";
                // saveImage(folderPath, results);            // Not a folder path
                saveImage(folderPath+"/"+filename, results);  // give filename 
        }
    }
}

推荐阅读