ImagePathToBitmapConverter.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Drawing;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Reflection;
  5. using Avalonia;
  6. using Avalonia.Platform;
  7. using Avalonia.Svg.Skia;
  8. using PixiEditor.AvaloniaUI.Helpers.Extensions;
  9. using Bitmap = Avalonia.Media.Imaging.Bitmap;
  10. namespace PixiEditor.AvaloniaUI.Helpers.Converters;
  11. internal class ImagePathToBitmapConverter : SingleInstanceConverter<ImagePathToBitmapConverter>
  12. {
  13. public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  14. {
  15. if (value is not string path)
  16. return AvaloniaProperty.UnsetValue;
  17. try
  18. {
  19. return LoadBitmapFromRelativePath(path);
  20. }
  21. catch (FileNotFoundException)
  22. {
  23. return AvaloniaProperty.UnsetValue;
  24. }
  25. }
  26. public static Bitmap LoadBitmapFromRelativePath(string path)
  27. {
  28. Uri uri = new($"avares://{Assembly.GetExecutingAssembly().FullName}{path}");
  29. if (!AssetLoader.Exists(uri))
  30. throw new FileNotFoundException($"Could not find asset with path {path}");
  31. return new Bitmap(AssetLoader.Open(uri));
  32. }
  33. public static DrawingApi.Core.Surface.Bitmap LoadDrawingApiBitmapFromRelativePath(string path)
  34. {
  35. Uri uri = new($"avares://{Assembly.GetExecutingAssembly().FullName}{path}");
  36. if (!AssetLoader.Exists(uri))
  37. throw new FileNotFoundException($"Could not find asset with path {path}");
  38. return BitmapExtensions.FromStream(AssetLoader.Open(uri));
  39. }
  40. public static Bitmap? TryLoadBitmapFromRelativePath(string path)
  41. {
  42. Uri uri = new($"avares://{Assembly.GetExecutingAssembly().FullName}{path}");
  43. return !AssetLoader.Exists(uri) ? null : new Bitmap(AssetLoader.Open(uri));
  44. }
  45. }