Skip to content

Commit

Permalink
add error handling to iconex getimagesource
Browse files Browse the repository at this point in the history
  • Loading branch information
bluepilledgreat committed Sep 21, 2024
1 parent c58a8ab commit 9f7e989
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
19 changes: 16 additions & 3 deletions Bloxstrap/Extensions/IconEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,22 @@ public static class IconEx

public static ImageSource GetImageSource(this Icon icon)
{
using MemoryStream stream = new();
icon.Save(stream);
return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
const string LOG_IDENT = "IconEx::GetImageSource";

try
{
using MemoryStream stream = new();
icon.Save(stream);
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();
}
}
}
}
14 changes: 14 additions & 0 deletions Bloxstrap/Utilities.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace Bloxstrap
{
Expand Down Expand Up @@ -81,5 +83,17 @@ public static Process[] GetProcessesSafe()
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);
}
}
}

0 comments on commit 9f7e989

Please sign in to comment.