LoginSignup
2
1

More than 1 year has passed since last update.

[C# / WPF] Windows で アカウントに設定された画像を取得して表示する (Windows.System.User.GetPropertyAsync → BitmapImage)

Last updated at Posted at 2022-10-11

概要

  • .NET 6.0 な WPF アプリで、User アカウントに設定された画像を取得して、XAMLで表示する。
  • 画像の取得は、WinRT な Windows.System.User.GetPropertyAsync で行う。
  • GetPropertyAsync で取得した IRandomAccessStreamReference を WPF の BitmapImage に変換して表示する。
  • サンプルアプリケーションはこちら

ユーザ情報の取得

IRandomAccessStreamReference を BitmapImage に変換して表示する

User.GetPictureAsync の See also で紹介されている、Windows-universal-samples/Samples/UserInfo/ では、下記のようなコードで BitmapImage に変換していますが、この場合(UWP)のBitmapImage は、Windows.UI.Xaml.Media.Imaging.BitmapImage で、WPF の System.Windows.Media.Imaging.BitmapImage では、BitmapImage.SetSource が存在せず、WPFおいてそのままでは使えません。

IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size64x64);
if (streamReference != null)
{
    IRandomAccessStream stream = await streamReference.OpenReadAsync();
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(stream);
    ProfileImage.Source = bitmapImage;
}

そこで、C# converting UWP BitmapImage to WPF BitmapImage で回答されているように、Stream に変換してから BitmapImage.StreamSource に設定することで、WPF で表示できるようになります。

var user = (await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated)).FirstOrDefault();

// C# converting UWP BitmapImage to WPF BitmapImage
// https://stackoverflow.com/questions/50596735/c-sharp-converting-uwp-bitmapimage-to-wpf-bitmapimage
IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size208x208);
if (streamReference != null)
{
    var bitmap = new BitmapImage();
    using var randomAccessStream = await streamReference.OpenReadAsync();
    using var stream = randomAccessStream.AsStream();

    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
    UserPicture.Value = bitmap;
}

サンプルコード

詳細は、サンプルアプリケーション を見てください。

実行すると下記の画像のようにログインしているユーザーのプロフィール画像が表示されます。

スクリーンショット 2022-10-12 002759.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1