private static IEnumerator GetDefaultAvatarTexture(this DiscordRPC.User user, DiscordRPC.User.AvatarSize size = DiscordRPC.User.AvatarSize.x128, AvatarDownloadCallback callback = null) { int discrim = user.Discriminator % 5; string filename = string.Format("default-{0}{1}.png", discrim, size.ToString()); string path = Path.Combine(_cache, filename); Texture2D texture; //Check if the file exists if (File.Exists(path)) { //Load the image var bytes = File.ReadAllBytes(path); texture = new Texture2D((int)size, (int)size, TextureFormat.RGBA32, false); texture.LoadImage(bytes); } else { string url = string.Format("https://{0}/embed/avatars/{1}.png?size={2}", user.CdnEndpoint, discrim, size); using (WWW www = new WWW(url)) { //Download the texture yield return(www); //Set the texture texture = www.texture; //Save the texture, making a cache for later if (!Directory.Exists(_cache)) { Directory.CreateDirectory(_cache); } var bytes = texture.EncodeToPNG(); File.WriteAllBytes(path, bytes); } } //Execute the callback (if any) if (callback != null) { callback.Invoke(user, texture); } }
private static IEnumerator EnumerateAvatarTexture(this DiscordRPC.User user, DiscordRPC.User.AvatarSize size = DiscordRPC.User.AvatarSize.x128, TextureFormat format = TextureFormat.RGBA32, bool isJPEG = false, AvatarDownloadCallback callback = null) { if (string.IsNullOrEmpty(user.Avatar)) { yield return(GetDefaultAvatarTexture(user, size, callback)); } else { //Generate the path name string filename = string.Format("{0}-{1}{2}.{3}", user.Discriminator, user.Avatar, size.ToString(), isJPEG ? "jpeg" : "png"); string path = Path.Combine(_cache, filename); //The holder texture is null, so we should create new one Texture2D holder = new Texture2D((int)size, (int)size, format, false); //Check if the file exists if (File.Exists(path)) { //Load the image var bytes = File.ReadAllBytes(path); holder.LoadImage(bytes); } else { using (WWW www = new WWW(user.GetAvatarURL(isJPEG ? DiscordRPC.User.AvatarFormat.JPEG : DiscordRPC.User.AvatarFormat.PNG, size))) { //Download the texture yield return(www); //Update the holder www.LoadImageIntoTexture(holder); //Save the texture, making a cache for later if (!Directory.Exists(_cache)) { Directory.CreateDirectory(_cache); } var bytes = isJPEG ? holder.EncodeToJPG(JpegQuality) : holder.EncodeToPNG(); File.WriteAllBytes(path, bytes); } } //Execute the callback (if any) if (callback != null) { callback.Invoke(user, holder); } } }