1
- using System . Drawing ;
1
+ using System . Buffers ;
2
+ using System . Drawing ;
2
3
using System . Drawing . Imaging ;
3
4
using StableDiffusion . NET . Helper . Images . Colors ;
4
5
using StableDiffusion . NET . Helper . Images ;
5
6
using System . IO ;
7
+ using System . Runtime . InteropServices ;
6
8
7
9
namespace ImageCreationUI ;
8
10
@@ -42,4 +44,34 @@ public static byte[] ToPng(this IImage image)
42
44
43
45
return ms . ToArray ( ) ;
44
46
}
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
+ }
45
77
}
0 commit comments