FileSaverHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using Avalonia.Media.Imaging;
  2. using PicView.Avalonia.ImageHandling;
  3. using PicView.Avalonia.ViewModels;
  4. using PicView.Core.ImageDecoding;
  5. namespace PicView.Avalonia.FileSystem;
  6. public static class FileSaverHelper
  7. {
  8. public static async Task SaveCurrentFile(MainViewModel vm)
  9. {
  10. if (vm is null)
  11. {
  12. return;
  13. }
  14. if (vm.FileInfo is null)
  15. {
  16. await SaveFileAsync(null, vm.FileInfo.FullName, vm);
  17. }
  18. else
  19. {
  20. await SaveFileAsync(vm.FileInfo.FullName, vm.FileInfo.FullName, vm);
  21. }
  22. //TODO: Add visual design to tell the user that file was saved
  23. }
  24. public static async Task SaveFileAs(MainViewModel vm)
  25. {
  26. if (vm is null)
  27. {
  28. return;
  29. }
  30. if (vm.FileInfo is null)
  31. {
  32. await SaveFileAsync(null, vm.FileInfo.FullName, vm);
  33. }
  34. else
  35. {
  36. await FilePicker.PickAndSaveFileAsAsync(vm.FileInfo.FullName, vm);
  37. }
  38. }
  39. public static async Task SaveFileAsync(string? filename, string destination, MainViewModel vm)
  40. {
  41. if (!string.IsNullOrWhiteSpace(filename))
  42. {
  43. await SaveImageFileHelper.SaveImageAsync(null,
  44. filename,
  45. destination,
  46. null,
  47. null,
  48. null,
  49. Path.GetExtension(destination),
  50. vm.RotationAngle);
  51. }
  52. else
  53. {
  54. switch (vm.ImageType)
  55. {
  56. case ImageType.AnimatedGif:
  57. case ImageType.AnimatedWebp:
  58. throw new ArgumentOutOfRangeException();
  59. case ImageType.Bitmap:
  60. if (vm.ImageSource is not Bitmap bitmap)
  61. {
  62. throw new ArgumentOutOfRangeException();
  63. }
  64. var stream = new FileStream(destination, FileMode.Create);
  65. const uint quality = 100;
  66. bitmap.Save(stream, (int)quality);
  67. await stream.DisposeAsync();
  68. var ext = Path.GetExtension(destination);
  69. if (ext != ".jpg" || ext != ".jpeg" || ext != ".png" || ext != ".bmp" || vm.RotationAngle != 0)
  70. {
  71. await SaveImageFileHelper.SaveImageAsync(
  72. null,
  73. destination,
  74. destination:destination,
  75. width: null,
  76. height: null,
  77. quality,
  78. ext,
  79. vm.RotationAngle);
  80. }
  81. break;
  82. case ImageType.Svg:
  83. throw new ArgumentOutOfRangeException();
  84. default:
  85. throw new ArgumentOutOfRangeException();
  86. }
  87. }
  88. }
  89. }