首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 圖片轉點陣數據:LockBits 快速訪問像素生成位圖陣列

     編輯:程式設計綜合問答

核心代碼

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 字庫生成。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved