add error handling to iconex getimagesource

This commit is contained in:
bluepilledgreat 2024-09-21 18:46:33 +01:00
parent c58a8ab739
commit 9f7e989e6b
2 changed files with 30 additions and 3 deletions

View File

@ -9,10 +9,23 @@ namespace Bloxstrap.Extensions
public static Icon GetSized(this Icon icon, int width, int height) => new(icon, new Size(width, height)); public static Icon GetSized(this Icon icon, int width, int height) => new(icon, new Size(width, height));
public static ImageSource GetImageSource(this Icon icon) public static ImageSource GetImageSource(this Icon icon)
{
const string LOG_IDENT = "IconEx::GetImageSource";
try
{ {
using MemoryStream stream = new(); using MemoryStream stream = new();
icon.Save(stream); icon.Save(stream);
return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
} }
catch (Exception ex)
{
App.Logger.WriteLine(LOG_IDENT, "Failed to get ImageSource");
App.Logger.WriteException(LOG_IDENT, ex);
// return fallback image
return Utilities.GetEmptyBitmap();
}
}
} }
} }

View File

@ -1,4 +1,6 @@
using System.ComponentModel; using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Windows.Media;
namespace Bloxstrap namespace Bloxstrap
{ {
@ -81,5 +83,17 @@ namespace Bloxstrap
return Array.Empty<Process>(); // can we retry? return Array.Empty<Process>(); // can we retry?
} }
} }
private static BitmapSource? _emptyBitmap;
public static BitmapSource GetEmptyBitmap()
{
return _emptyBitmap ??= CreateEmptyBitmap();
}
// https://stackoverflow.com/a/50316845
public static BitmapSource CreateEmptyBitmap()
{
return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] { 0 }, 1);
}
} }
} }