diff --git a/src/System.Drawing.Common/tests/System/Drawing/ImageTests.cs b/src/System.Drawing.Common/tests/System/Drawing/ImageTests.cs index 16e0bd70193..2a8db2a1199 100644 --- a/src/System.Drawing.Common/tests/System/Drawing/ImageTests.cs +++ b/src/System.Drawing.Common/tests/System/Drawing/ImageTests.cs @@ -19,6 +19,39 @@ public class ImageTests private const int PropertyTagTypeASCII = 2; private const int PropertyTagTypeShort = 3; + [Fact] + public void Save_StreamImageFormat_DoesNotGrowNativeMemoryAcrossCollections() + { + if (PlatformDetection.IsNetFramework) + { + Assert.Skip("Regression is tracked for System.Drawing.Common 9+ path used in .NET."); + } + + const int iterationCount = 500; + const long allowedGrowthBytes = 64L * 1024 * 1024; + + static long NativeMemory() => + Process.GetCurrentProcess().PrivateMemorySize64 - GC.GetGCMemoryInfo().TotalCommittedBytes; + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + long before = NativeMemory(); + + for (int i = 0; i < iterationCount; i++) + { + new Bitmap(1500, 1500).Save(new MemoryStream(), ImageFormat.Bmp); + } + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + long leakedBytes = NativeMemory() - before; + Assert.True(leakedBytes < allowedGrowthBytes, $"Unexpected native memory growth: {leakedBytes / 1024 / 1024} MB"); + } + [Fact] public void PropertyIdList_GetBitmapJpg_Success() { diff --git a/src/System.Private.Windows.GdiPlus/System/Drawing/CoreImageExtensions.cs b/src/System.Private.Windows.GdiPlus/System/Drawing/CoreImageExtensions.cs index 1dd0a451ec9..37ca533c209 100644 --- a/src/System.Private.Windows.GdiPlus/System/Drawing/CoreImageExtensions.cs +++ b/src/System.Private.Windows.GdiPlus/System/Drawing/CoreImageExtensions.cs @@ -25,7 +25,14 @@ internal static void Save(this IImage image, Stream stream, Guid encoder, Guid f } using var iStream = stream.ToIStream(); - PInvokeGdiPlus.GdipSaveImageToStream(image.GetPointer(), iStream, &encoder, encoderParameters).ThrowIfFailed(); + try + { + PInvokeGdiPlus.GdipSaveImageToStream(image.GetPointer(), iStream, &encoder, encoderParameters).ThrowIfFailed(); + } + finally + { + GC.KeepAlive(image); + } } internal static void Save(this IImage image, MemoryStream stream)