unity3d - 下载图像并保存到设备
问题描述
我在这里遇到了 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);
}
}
解决方案
- 您的文件名错误,因此请提供带有扩展名的文件名,
- 如果你不提供扩展名,'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
}
}
}
推荐阅读
- r - 如何根据元素的属性对R中的列表进行排序
- css - “之前”元素的 CSS 定位
- php - 如何在 php 中调用 Vimeo API?
- reactjs - 跨环境 NODE_ENV=开发 npm 运行 webpack-development
- php - 呈现表单时未找到块“表单”。在单独类中的控制器外部的 Symfony 应用程序中
- c++ - C++ 将函数调用列表作为参数传递
- google-sheets - 如果值介于 10 和 20 之间,则在另一个单元格中显示 20% 的值
- android - 为 ConstraintLayout 添加样式
- android - 如何在android中按大数四舍五入
- python - 如何使用python从word文件中的表格中提取阿拉伯语文本