最近在接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 ;
}