Skip to content

Instantly share code, notes, and snippets.

@mabster
Last active February 13, 2022 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mabster/70cb40c904f9774b7b70b8a87e6281fb to your computer and use it in GitHub Desktop.
Save mabster/70cb40c904f9774b7b70b8a87e6281fb to your computer and use it in GitHub Desktop.
UserPhoto Blazor Component
@inject GraphServiceClient GraphClient
<AuthorizeView>
<Authorized>
<img src="@_src"
title="@_title"
onerror="this.src = '@DEFAULT';"
class="rounded-circle img-fluid"
@attributes="AdditionalAttributes" />
</Authorized>
<NotAuthorized>
<img src="@DEFAULT"
title="Sign In"
class="rounded-circle img-fluid"
@attributes="AdditionalAttributes" />
</NotAuthorized>
</AuthorizeView>
@code {
[Parameter]
public string? Id { get; set; }
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> AdditionalAttributes { get; set; } = new();
const string DEFAULT = "<img in project or data uri>";
string _src = DEFAULT;
string _title = "Unknown User";
static Dictionary<string, (string src, string title)> _cache = new();
protected async override Task OnInitializedAsync()
{
if (String.IsNullOrEmpty(Id)) return;
if (_cache.TryGetValue(Id, out var cache))
{
_src = cache.src;
_title = cache.title;
return;
}
var photo = await GraphClient.Users[Id].Photo.Content.Request().GetAsync();
if (photo != null)
{
var ms = new System.IO.MemoryStream();
await photo.CopyToAsync(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
_src = string.Format("data:image/png;base64,{0}", result);
}
var user = await GraphClient.Users[Id].Request().GetAsync();
_title = user?.DisplayName ?? "Unknown User";
_cache.TryAdd(Id, (_src, _title));
}
}
@mabster
Copy link
Author

mabster commented Sep 23, 2021

Interestingly, the "border-radius: 50%" style works if it's in UserPhoto.razor.css, but doesn't seem to work if it's inline like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment