From 8f99e38f99a1dbd75333f6e4905f9fa999b382e5 Mon Sep 17 00:00:00 2001 From: Darth Affe Date: Sat, 27 Apr 2024 17:21:09 +0200 Subject: [PATCH] Added BitmapToImage-Helper Method to example project --- .../Extensions/ImageExtension.cs | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Examples/ImageCreationUI/Extensions/ImageExtension.cs b/Examples/ImageCreationUI/Extensions/ImageExtension.cs index dbc7e3e..07d4d9c 100644 --- a/Examples/ImageCreationUI/Extensions/ImageExtension.cs +++ b/Examples/ImageCreationUI/Extensions/ImageExtension.cs @@ -1,8 +1,10 @@ -using System.Drawing; +using System.Buffers; +using System.Drawing; using System.Drawing.Imaging; using StableDiffusion.NET.Helper.Images.Colors; using StableDiffusion.NET.Helper.Images; using System.IO; +using System.Runtime.InteropServices; namespace ImageCreationUI; @@ -42,4 +44,34 @@ public static class ImageExtension return ms.ToArray(); } + + public static unsafe Image ToImage(this Bitmap bitmap) + { + int width = bitmap.Width; + int height = bitmap.Height; + + byte[] buffer = new byte[height * width * ColorRGB.ColorFormat.BytesPerPixel]; + Span colorBuffer = MemoryMarshal.Cast(buffer); + + Rectangle rect = new(0, 0, bitmap.Width, bitmap.Height); + BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat); + + nint ptr = bmpData.Scan0; + for (int y = 0; y < height; y++) + { + Span source = new((void*)ptr, bmpData.Stride); + Span target = colorBuffer.Slice(y * width, width); + for (int x = 0; x < width; x++) + { + ColorBGR srcColor = source[x]; + target[x] = new ColorRGB(srcColor.R, srcColor.G, srcColor.B); + } + + ptr += bmpData.Stride; + } + + bitmap.UnlockBits(bmpData); + + return new Image(buffer, 0, 0, width, height, width); + } } \ No newline at end of file