通过在线源统一在手机上保存图像

主要目标:从在线url加载图像,然后在移动设备上的/ Repo / {VenueName}目录中本地保存图像(任何类型)。 这样就可以节省未来的移动数据,当场景加载首先检查本地图像然后调用www请求,如果它已经不存在于移动设备上。

我已经在线获取图像,我从json文件中提取了url,现在我想将它们本地存储在移动设备上,以便为最终用户保存数据传输。

我已经绕过具有持久数据路径和IO.directories的圈子并继续遇到问题。

目前我有一个从在线保存文本并成功将其存储在设备上的function,但如果我将它用于图像,由于下面显示的字符串参数,它将无法工作,我试图将其转换为字节编辑function也不是通过它www.text并得到图像损坏错误。

这是我用于文本保存文件的旧function。

public void writeStringToFile( string str, string filename ){ #if !WEB_BUILD string path = pathForDocumentsFile( filename ); FileStream file = new FileStream (path, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter( file ); sw.WriteLine( str ); sw.Close(); file.Close(); #endif } public string pathForDocumentsFile( string filename ){ if (Application.platform == RuntimePlatform.IPhonePlayer) { string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5 ); path = path.Substring( 0, path.LastIndexOf( '/' ) ); return Path.Combine( Path.Combine( path, "Documents" ), filename ); }else if(Application.platform == RuntimePlatform.Android){ string path = Application.persistentDataPath; path = path.Substring(0, path.LastIndexOf( '/' ) ); return Path.Combine (path, filename); }else { string path = Application.dataPath; path = path.Substring(0, path.LastIndexOf( '/' ) ); return Path.Combine (path, filename); } } 

这适用于文本,因为它期望一个字符串,但无论我编辑多少,我都无法在图像上工作。

我最终走了一条不同的路线但是使用以下代码进行了未经授权的访问问题,并且认为它不适用于移动设备但是…

 IEnumerator loadPic(WWW www, string thefile, string folder) { yield return www; string venue = Application.persistentDataPath + folder; string path = Application.persistentDataPath + folder + "/" + thefile; if (!System.IO.Directory.Exists(venue)) { System.IO.Directory.CreateDirectory(venue); } if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } System.IO.File.WriteAllBytes(path, www.bytes); } 

呃,这是凌晨3点,我无法弄明白,你们可以帮助我吗? 提前致谢。

我试图将它转换为字节编辑function,而不是传递它www.text并得到图像损坏错误

这可能是你问题的90%的原因。 WWW.text用于非二进制数据,例如简单文本。

1.使用WWW.bytes而不是WWW.text下载图像或文件。

2.使用 File.WriteAllBytes保存图像。

3。使用File.ReadAllBytes读取图像。

4.使用Texture2D.LoadImage(yourImageByteArray);图像加载到纹理Texture2D.LoadImage(yourImageByteArray);

5.如果您希望此路径与每个平台兼容,则您的路径必须是Application.persistentDataPath/yourfolderName/thenFileName 。 它不应该Application.persistentDataPath/yourFileNameApplication.dataPath

6.最后,使用Debug.Log查看代码中发生了什么。 您必须或至少使用调试器。 您需要确切知道代码失败的位置。

您仍然需要执行一些错误检查。

 public void downloadImage(string url, string pathToSaveImage) { WWW www = new WWW(url); StartCoroutine(_downloadImage(www, pathToSaveImage)); } private IEnumerator _downloadImage(WWW www, string savePath) { yield return www; //Check if we failed to send if (string.IsNullOrEmpty(www.error)) { UnityEngine.Debug.Log("Success"); //Save Image saveImage(savePath, www.bytes); } else { UnityEngine.Debug.Log("Error: " + www.error); } } void saveImage(string path, byte[] imageBytes) { //Create Directory if it does not exist if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } 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); } } byte[] loadImage(string path) { byte[] dataByte = null; //Exit if Directory or File does not exist if (!Directory.Exists(Path.GetDirectoryName(path))) { Debug.LogWarning("Directory does not exist"); return null; } if (!File.Exists(path)) { Debug.Log("File does not exist"); return null; } try { dataByte = File.ReadAllBytes(path); Debug.Log("Loaded Data from: " + path.Replace("/", "\\")); } catch (Exception e) { Debug.LogWarning("Failed To Load Data from: " + path.Replace("/", "\\")); Debug.LogWarning("Error: " + e.Message); } return dataByte; } 

用法

准备url从中下载图像并保存到:

 //File url string url = "http://sofzh.miximages.com/c%23/Cool-Wallpaper-11C4.jpg"; //Save Path string savePath = Path.Combine(Application.persistentDataPath, "data"); savePath = Path.Combine(savePath, "Images"); savePath = Path.Combine(savePath, "logo"); 

如您所见,无需将图像扩展名( pngjpg )添加到savePath也不应在保存路径中添加图像扩展名。 如果您不知道扩展名,这将使以后加载更容易。 只要图像是pngjpg图像格式,它就应该工作。

下载文件:

 downloadImage(url, savePath); 

从文件加载图像:

 byte[] imageBytes = loadImage(savePath); 

将图像放到Texture2D:

 Texture2D texture; texture = new Texture2D(2, 2); texture.LoadImage(imageBytes);