unity 文件、图片加载与保存

using UnityEngine;
02. using System.Collections;
03. using System.IO;
04.  
05. public class AsyncImageDownload :MonoBehaviour {
06.  
07. public  Texture placeholder;
08. public static AsyncImageDownload  Instance=null;
09.  
10. private   string path=Application.persistentDataPath+"/ImageCache/" ;
11.  
12. //构建单例
13. public static AsyncImageDownload CreateSingleton()
14. {
15. if (!Directory.Exists(Application.persistentDataPath+"/ImageCache/")) {
16. Directory.CreateDirectory(Application.persistentDataPath+"/ImageCache/");
17. }
18.  
19. GameObject obj = new GameObject ();
20. obj.AddComponent<AsyncImageDownload> ();
21.  
22. AsyncImageDownload loader= obj.GetComponent<AsyncImageDownload>();
23. Instance=loader;
24. loader.placeholder=Resources.Load("placeholder") as Texture;
25. return loader;
26.  
27. }
28.  
29.  
30. public  void SetAsyncImage(string url,UITexture texture){
31.  
32.  
33.  
34. //开始下载图片前,将UITexture的主图片设置为占位图
35. texture.mainTexture = placeholder;
36.  
37. //判断是否是第一次加载这张图片
38.  
39. if (!File.Exists (path + url.GetHashCode())) {
40. //如果之前不存在缓存文件
41.  
42.  
43. StartCoroutine (DownloadImage (url, texture));
44.  
45.  
46. }
47. else {
48.  
49. StartCoroutine(LoadLocalImage(url,texture));
50.  
51. }
52.  
53. }
54.  
55. IEnumerator  DownloadImage(string url,UITexture texture){
56. Debug.Log("downloading new image:"+path+url.GetHashCode());
57. WWW www = new WWW (url);
58. yield return www;
59.  
60. Texture2D image = www.texture;
61. //将图片保存至缓存路径
62. byte[] pngData = image.EncodeToPNG(); 
63. File.WriteAllBytes(path+url.GetHashCode(), pngData); 
64.  
65. texture.mainTexture = image;
66.  
67. }
68.  
69. IEnumerator  LoadLocalImage(string url,UITexture texture){
70. string filePath = "file:///" + path + url.GetHashCode ();
71.  
72. Debug.Log("getting local image:"+filePath);
73. WWW www = new WWW (filePath);
74. yield return www;
75.  
76.  
77. //直接贴图
78. texture.mainTexture = www.texture;
79.  
80. }
81. }




1.最近我也碰到过这个问题,我是这样解决的。

1.将文件下载完成
2.通过URL获取文件名字(类型包括在里面了)
3.通过字节的形式,以写文件的方式写到本地。
直接上代码:
    private IEnumerator DownLoadToLocal(string url, string  number)
    {
        WWW www = new WWW(url);
        string img_name = url.Substring(url.LastIndexOf('/') + 1); //根据URL获取文件的名字。
        yield return www;
        if ( www.error  == null)
        {
                FileStream fs = File.Create(path + img_name); //path为你想保存文件的路径。
                fs.Write( www.bytes , 0,  www.bytes.Length );
                fs.Close();
        }
        else
        {
            Debug.Log( www.error );
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值