From 276d8448283cdebc724c6c65f67ba4e1a40c0452 Mon Sep 17 00:00:00 2001 From: "Konstantin S." Date: Sat, 11 Apr 2026 05:12:37 +0400 Subject: [PATCH] fix: convert png IconSource streams to icons --- .../System.Drawing/StreamExtensions.cs | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/libs/H.NotifyIcon.Shared/Utilities/System.Drawing/StreamExtensions.cs b/src/libs/H.NotifyIcon.Shared/Utilities/System.Drawing/StreamExtensions.cs index e9fca1ff..72235183 100644 --- a/src/libs/H.NotifyIcon.Shared/Utilities/System.Drawing/StreamExtensions.cs +++ b/src/libs/H.NotifyIcon.Shared/Utilities/System.Drawing/StreamExtensions.cs @@ -8,8 +8,8 @@ internal static class StreamExtensions internal static Icon ToSmallIcon(this Stream stream) { var iconSize = IconUtilities.GetRequiredCustomIconSize(largeIcon: false).ScaleWithDpi(); - - return new Icon(stream, iconSize); + using var iconStream = stream.ToIconStream(); + return new Icon(iconStream, iconSize); } [SupportedOSPlatform("windows")] @@ -25,4 +25,34 @@ internal static (int Width, int Height, int BitsPerPixel) GetMetadata(this Strea return (image.Width, image.Height, System.Drawing.Image.GetPixelFormatSize(image.PixelFormat)); } + + [SupportedOSPlatform("windows")] + private static MemoryStream ToIconStream(this Stream stream) + { + if (stream == null) + { + throw new ArgumentNullException(nameof(stream)); + } + + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + + var data = buffer.ToArray(); + var iconData = IsPng(data) ? data.ConvertPngToIco() : data; + + return new MemoryStream(iconData, writable: false); + } + + private static bool IsPng(byte[] data) + { + return data.Length >= 8 && + data[0] == 0x89 && + data[1] == 0x50 && + data[2] == 0x4E && + data[3] == 0x47 && + data[4] == 0x0D && + data[5] == 0x0A && + data[6] == 0x1A && + data[7] == 0x0A; + } }