核心代碼
public static byte[] ImageToDotMatrix(Bitmap bmp, int threshold = 128) {
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
var bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int stride = bmpData.Stride;
byte[] pixels = new byte[stride * bmp.Height];
Marshal.Copy(bmpData.Scan0, pixels, 0, pixels.Length);
bmp.UnlockBits(bmpData);
// 簡單二值化:每 4 字節 (BGRA) 取灰度
var dots = new List();
for (int y = 0; y < bmp.Height; y++) {
byte rowByte = 0;
for (int x = 0; x < bmp.Width; x++) {
int idx = y * stride + x * 4;
int gray = (pixels[idx] + pixels[idx+1] + pixels[idx+2]) / 3;
if (gray < threshold) rowByte |= (byte)(1 << (7 - (x % 8)));
if ((x % 8) == 7 || x == bmp.Width - 1) dots.Add(rowByte);
}
}
return dots.ToArray(); // 每字節 8 點,MSB first
}
說明
- `LockBits` + `Marshal.Copy` 比 `GetPixel` 快 100 倍以上。
- 輸出格式可根據下游設備調整 (LSB first、行序、填充)。
- 參考完整字庫生成專案:CSDN 字庫生成。