From 46bba39c4ab44312634e94374213d4b8afbd8cc0 Mon Sep 17 00:00:00 2001 From: Darth Affe Date: Thu, 17 Oct 2024 21:19:38 +0200 Subject: [PATCH] Fixed wrong free of upscaled images --- StableDiffusion.NET/Helper/ImageHelper.cs | 22 +++++++++++++++------- StableDiffusion.NET/Models/UpscaleModel.cs | 4 ++-- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/StableDiffusion.NET/Helper/ImageHelper.cs b/StableDiffusion.NET/Helper/ImageHelper.cs index dbccb15..1c38a31 100644 --- a/StableDiffusion.NET/Helper/ImageHelper.cs +++ b/StableDiffusion.NET/Helper/ImageHelper.cs @@ -8,21 +8,29 @@ internal static class ImageHelper { public static unsafe Image ToImage(Native.sd_image_t* sdImage) { - int width = (int)sdImage->width; - int height = (int)sdImage->height; - int bpp = (int)sdImage->channel; + Image image = ToImage(*sdImage); - Image image = Image.Create(new ReadOnlySpan(sdImage->data, width * height * bpp), width, height, width * bpp); + Marshal.FreeHGlobal((nint)sdImage); + + return image; + } + + public static unsafe Image ToImage(Native.sd_image_t sdImage) + { + int width = (int)sdImage.width; + int height = (int)sdImage.height; + int bpp = (int)sdImage.channel; + + Image image = Image.Create(new ReadOnlySpan(sdImage.data, width * height * bpp), width, height, width * bpp); Dispose(sdImage); return image; } - public static unsafe void Dispose(Native.sd_image_t* image) + public static unsafe void Dispose(Native.sd_image_t image) { - Marshal.FreeHGlobal((nint)image->data); - Marshal.FreeHGlobal((nint)image); + Marshal.FreeHGlobal((nint)image.data); } public static unsafe Native.sd_image_t ToSdImage(this IImage image, byte* pinnedReference) diff --git a/StableDiffusion.NET/Models/UpscaleModel.cs b/StableDiffusion.NET/Models/UpscaleModel.cs index eb7e610..600f5b3 100644 --- a/StableDiffusion.NET/Models/UpscaleModel.cs +++ b/StableDiffusion.NET/Models/UpscaleModel.cs @@ -58,14 +58,14 @@ public sealed unsafe class UpscaleModel : IDisposable fixed (byte* imagePtr = sourceImage.AsRefImage()) { Native.sd_image_t result = Native.upscale(_ctx, sourceImage.ToSdImage(imagePtr), upscaleFactor); - return ImageHelper.ToImage(&result); + return ImageHelper.ToImage(result); } } private IImage Upscale(Native.sd_image_t image, int upscaleFactor) { Native.sd_image_t result = Native.upscale(_ctx, image, upscaleFactor); - return ImageHelper.ToImage(&result); + return ImageHelper.ToImage(result); } public void Dispose()