回答編集履歴

1

コメントを受け変換部追記。

2020/01/13 03:03

投稿

退会済みユーザー
test CHANGED
@@ -37,3 +37,129 @@
37
37
 
38
38
 
39
39
  あと、質問を編集しただけでは私には通知が来ないようなので回答にコメントしてもらえると反応が早いかもしれません。
40
+
41
+
42
+
43
+ 【コメントを受け追記】
44
+
45
+ 減色済みの奴が対象で減勘だけするならこんな感じで良いはず。
46
+
47
+ 例外処理とか諸々省略してるので注意。
48
+
49
+ ```C#
50
+
51
+ static Bitmap ImageConvert24bitTo8bit(Bitmap bmpSource)
52
+
53
+ {
54
+
55
+ Bitmap bmp8bit = new Bitmap(bmpSource.Width, bmpSource.Height, PixelFormat.Format8bppIndexed);
56
+
57
+
58
+
59
+ BitmapData bmpData8bit = bmp8bit.LockBits(
60
+
61
+ new Rectangle(0, 0, bmp8bit.Width, bmp8bit.Height),
62
+
63
+ ImageLockMode.WriteOnly,
64
+
65
+ bmp8bit.PixelFormat
66
+
67
+ );
68
+
69
+
70
+
71
+ BitmapData bmpData24bit = bmpSource.LockBits(
72
+
73
+ new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
74
+
75
+ ImageLockMode.ReadOnly,
76
+
77
+ bmpSource.PixelFormat
78
+
79
+ );
80
+
81
+
82
+
83
+ byte[] imgBuf8bit = new byte[bmpData8bit.Stride * bmp8bit.Height];
84
+
85
+ byte[] imgBuf24bit = new byte[bmpData24bit.Stride * bmpSource.Height];
86
+
87
+
88
+
89
+ Marshal.Copy(bmpData24bit.Scan0, imgBuf24bit, 0, imgBuf24bit.Length);
90
+
91
+
92
+
93
+ var colors = new Dictionary<Color, byte>();
94
+
95
+ byte colorIndex = 0;
96
+
97
+
98
+
99
+ for (int y = 0; y < bmpSource.Height; y++)
100
+
101
+ {
102
+
103
+ for (int x = 0; x < bmpSource.Width; x++)
104
+
105
+ {
106
+
107
+ int index24bit = y * bmpData24bit.Stride + x * 3;
108
+
109
+ int index8bit = y * bmpData8bit.Stride + x;
110
+
111
+ byte b = imgBuf24bit[index24bit];
112
+
113
+ byte g = imgBuf24bit[index24bit + 1];
114
+
115
+ byte r = imgBuf24bit[index24bit + 2];
116
+
117
+
118
+
119
+ // 24bitから8bitへ
120
+
121
+ var color = Color.FromArgb(r, g, b);
122
+
123
+ if (colors.TryGetValue(color, out byte i))
124
+
125
+ imgBuf8bit[index8bit] = i;
126
+
127
+ else
128
+
129
+ {
130
+
131
+ imgBuf8bit[index8bit] = colorIndex;
132
+
133
+ colors.Add(color, colorIndex);
134
+
135
+ colorIndex++;
136
+
137
+ }
138
+
139
+ }
140
+
141
+ }
142
+
143
+ Marshal.Copy(imgBuf8bit, 0, bmpData8bit.Scan0, imgBuf8bit.Length);
144
+
145
+ bmpSource.UnlockBits(bmpData24bit);
146
+
147
+ bmp8bit.UnlockBits(bmpData8bit);
148
+
149
+
150
+
151
+ var pal = bmp8bit.Palette;
152
+
153
+ foreach (var item in colors)
154
+
155
+ pal.Entries[item.Value] = item.Key;
156
+
157
+ bmp8bit.Palette = pal;
158
+
159
+
160
+
161
+ return bmp8bit;
162
+
163
+ }
164
+
165
+ ```