Skip to content

Commit 8f99e38

Browse files
committed
Added BitmapToImage-Helper Method to example project
1 parent 09355fc commit 8f99e38

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

Examples/ImageCreationUI/Extensions/ImageExtension.cs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
using System.Drawing;
1+
using System.Buffers;
2+
using System.Drawing;
23
using System.Drawing.Imaging;
34
using StableDiffusion.NET.Helper.Images.Colors;
45
using StableDiffusion.NET.Helper.Images;
56
using System.IO;
7+
using System.Runtime.InteropServices;
68

79
namespace ImageCreationUI;
810

@@ -42,4 +44,34 @@ public static byte[] ToPng(this IImage image)
4244

4345
return ms.ToArray();
4446
}
47+
48+
public static unsafe Image<ColorRGB> ToImage(this Bitmap bitmap)
49+
{
50+
int width = bitmap.Width;
51+
int height = bitmap.Height;
52+
53+
byte[] buffer = new byte[height * width * ColorRGB.ColorFormat.BytesPerPixel];
54+
Span<ColorRGB> colorBuffer = MemoryMarshal.Cast<byte, ColorRGB>(buffer);
55+
56+
Rectangle rect = new(0, 0, bitmap.Width, bitmap.Height);
57+
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
58+
59+
nint ptr = bmpData.Scan0;
60+
for (int y = 0; y < height; y++)
61+
{
62+
Span<ColorBGR> source = new((void*)ptr, bmpData.Stride);
63+
Span<ColorRGB> target = colorBuffer.Slice(y * width, width);
64+
for (int x = 0; x < width; x++)
65+
{
66+
ColorBGR srcColor = source[x];
67+
target[x] = new ColorRGB(srcColor.R, srcColor.G, srcColor.B);
68+
}
69+
70+
ptr += bmpData.Stride;
71+
}
72+
73+
bitmap.UnlockBits(bmpData);
74+
75+
return new Image<ColorRGB>(buffer, 0, 0, width, height, width);
76+
}
4577
}

0 commit comments

Comments
 (0)