JD2022-TU1/main/tools/modules/JD.Jira.WPF/View/AvatarCache.cs

67 lines
2 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;
using Ubisoft;
namespace JD.Jira.WPF.View
{
public static class AvatarCache
{
private static readonly Dictionary<string, BitmapImage> _cache = new Dictionary<string, BitmapImage>();
static AvatarCache()
{
DefaultAvatar = new BitmapImage(new Uri("pack://application:,,,/JD.Jira.WPF;component/Resources/avatar.png", UriKind.Absolute));
}
public static BitmapImage GetAvatar(string assignee, Atlassian.Jira.Jira jira)
{
if (_cache.ContainsKey(assignee))
{
return _cache[assignee];
}
try
{
var userPicture = ActiveDirectory.GetUserPicture(assignee);
if (userPicture == null || userPicture.Length == 0)
{
return DefaultAvatar;
}
var image = ByteArrayToBitmapImage(userPicture);
_cache.Add(assignee, image);
return image;
}
catch (Exception)
{
return DefaultAvatar;
}
}
public static BitmapImage DefaultAvatar { get; }
/// <summary>
/// Transform a byte array into a Bitmapimage
/// </summary>
/// <param name="array">List of bytes representing the image</param>
/// <returns>The byte array as a BitmapImage</returns>
public static BitmapImage ByteArrayToBitmapImage(byte[] array)
{
if (array == null || !array.Any())
return null;
using (var ms = new MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
image.Freeze();
return image;
}
}
}
}