PostViewModel.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Avalonia.Controls.ApplicationLifetimes;
  2. using Avalonia.Media.Imaging;
  3. using ReactiveUI;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using VeloeAvaloniaKemonoPartyApp.Models;
  10. namespace VeloeAvaloniaKemonoPartyApp.ViewModels
  11. {
  12. public class PostViewModel : ViewModelBase
  13. {
  14. private readonly Post _post;
  15. public PostViewModel(Post post)
  16. {
  17. _post = post;
  18. }
  19. public string Artist => _post.Content;
  20. public string Title => _post.Title;
  21. private Bitmap? _cover;
  22. public Bitmap? Cover
  23. {
  24. get => _cover;
  25. private set => this.RaiseAndSetIfChanged(ref _cover, value);
  26. }
  27. public async Task LoadAvatar()
  28. {
  29. if (_post.Attachments.Count == 0) return;
  30. await using (var imageStream = await _post.LoadCoverBitmapAsync())
  31. {
  32. Cover = await Task.Run(() =>
  33. {
  34. Bitmap? bitmap;
  35. try
  36. {
  37. bitmap = new Bitmap(imageStream);
  38. bitmap = bitmap.CreateScaledBitmap(new Avalonia.PixelSize(bitmap.PixelSize.Width / 2, bitmap.PixelSize.Height / 2));
  39. }
  40. catch (Exception ex)
  41. {
  42. bitmap = null;
  43. }
  44. return bitmap;
  45. });
  46. }
  47. }
  48. public async Task SaveToDiskAsync()
  49. {
  50. await _post.SaveAsync();
  51. if (Cover != null)
  52. {
  53. var bitmap = Cover;
  54. await Task.Run(() =>
  55. {
  56. using (var fs = _post.SaveCoverBitmapStream())
  57. {
  58. bitmap.Save(fs);
  59. }
  60. });
  61. }
  62. }
  63. }
  64. }