unity www缓存图片

在Unity中对接Kakao SDK时,需要请求并缓存好友头像。由于WWW.LoadFromCacheOrDownload的问题,改为使用WWW下载。方法包括检查图片是否已加载,未加载则从网络下载,已加载则从本地文件读取。以下是实现代码。
摘要由CSDN通过智能技术生成


最近在接SDK的时候,需要从韩国Kakao(类似于QQ和微信)上 ,需要请求好友的头像。

本来是想用uniy 的WWW.LoadFromCacheOrDownload函数的,但是提醒只能出错:WWWCached data can only be accessed using the assetBundle property! 

所以只能用WWW下载了。

实现大意:1.判断是否已经加载过图片。

     2.如果图片未加载过,从网上下载。

     3.如果图片加载过了,从文件中下载。

下面给出自用代码:

if (!completedLoadThumbnail && !string.IsNullOrEmpty (mKakaoFriendData. fInfo.profile_thumbnail_image ))
        {
            if (!File .Exists( Application.dataPath + "/Resources/My/" + mKakaoFriendData.fInfo .profile_thumbnail_image. GetHashCode()))
            {
                StartCoroutine(LoadThumbnail (mKakaoFriendData. fInfo.profile_thumbnail_image ));
            }
            else
            {
                StartCoroutine(LoadLocalImage (mKakaoFriendData. fInfo.profile_thumbnail_image ));
            }
          
        }

private IEnumerator LoadThumbnail (string url)
    {
        WWW www = new WWW((new Uri(url)).AbsoluteUri);
        yield return www;

        if (!string .IsNullOrEmpty( www.error ))
        {
            Debug.Log (string. Format("Failed to load image: {0}, {1}" , url, www.error));
            yield break ;
        }
        Texture2D image = www.texture;
        //    将图片保存至缓存路径
        byte[] pngData = image.EncodeToPNG();
        File.WriteAllBytes (Application. dataPath + "/Resources/My/" + url.GetHashCode(), pngData);
        mthumbnailImage.mainTexture = www.texture;
        completedLoadThumbnail = true ;
    }

  private IEnumerator LoadLocalImage (string url)
    {
        // 已在本地缓存
        string filePath = "file:///" + Application.dataPath + "/Resources/My/" + url.GetHashCode ();
        WWW www = new WWW(filePath);
        yield return www;
        mthumbnailImage.mainTexture = www.texture;
        completedLoadThumbnail = true ;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值