下载图像并保存到设备

时间:2020-06-11 06:34:41

标签: unity3d unitywebrequest

我在这里遇到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);
    }
}

1 个答案:

答案 0 :(得分:3)

  • 文件名错误,请给文件名加上扩展名,
  • 如果您不提供扩展名,则“ Directory.Exists”将不知道文件还是目录。
  • 或者您可以分隔参数,例如rootDirPath和filename。
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 
        }
    }
}