66using System ;
77using System . Collections . Generic ;
88using System . Linq ;
9+ using System . Numerics ;
910using System . Text ;
1011using System . Threading . Tasks ;
1112using DotNetCampus . MediaConverters . Imaging . Effect . Extensions ;
13+ using SixLabors . ImageSharp . Processing ;
1214
1315namespace DotNetCampus . MediaConverters . Imaging . Effect ;
1416
@@ -29,6 +31,47 @@ public static void ReplaceColor(this Image<Rgba32> bitmap, ColorMetadata sourceC
2931 color . IsNearlyEquals ( sourceColor ) ? targetColor : color ) ;
3032 }
3133
34+ /// <summary>
35+ /// 将图片<paramref name="image"/>上指定的颜色<paramref name="sourceColor"/>替换为颜色<paramref name="targetColor"/>
36+ /// </summary>
37+ /// <param name="image">图片</param>
38+ /// <param name="sourceColor">原始颜色</param>
39+ /// <param name="targetColor">目标颜色</param>
40+ public static void ReplaceColor ( this Image < Rgba32 > image , Rgba32 sourceColor , Rgba32 targetColor )
41+ {
42+ var sourceVector4 = sourceColor . ToVector4 ( ) ;
43+ var targetVector4 = targetColor . ToVector4 ( ) ;
44+
45+ var sourceMetadata = new ColorMetadata ( sourceColor ) ;
46+
47+ image . Mutate ( context =>
48+ {
49+ context . ProcessPixelRowsAsVector4 ( ( Span < Vector4 > row ) =>
50+ {
51+ for ( int i = 0 ; i < row . Length ; i ++ )
52+ {
53+ var current = row [ i ] ;
54+ if ( current . Equals ( sourceVector4 ) )
55+ {
56+ // 快速分支
57+ row [ i ] = targetVector4 ;
58+ }
59+ else
60+ {
61+ Rgba32 pixel = default ;
62+ pixel . FromVector4 ( current ) ;
63+
64+ var currentMetadata = new ColorMetadata ( pixel ) ;
65+ if ( currentMetadata . IsNearlyEquals ( sourceMetadata ) )
66+ {
67+ row [ i ] = targetVector4 ;
68+ }
69+ }
70+ }
71+ } ) ;
72+ } ) ;
73+ }
74+
3275 /// <summary>
3376 /// 将图片<paramref name="bitmap"/>上指定的一部分颜色替换为指定的对应颜色
3477 /// </summary>
0 commit comments