使用 GetDIBits 讀取 24 位元位圖,縱座標正常,橫座標卻循環位移:(5,8) (6,8) ... (0,8) (1,8)...。
Windows 位圖每行大小必須是 4 字節倍數。24 位元 (3 bytes/pixel) 時,寬度 9 像素 → 27 bytes,補齊到 28 bytes (4 的倍數)。記憶體佈局每行結尾有 1 個填充字節,導致邏輯座標偏移。
' 正確行寬計算 (包含填充)
Dim stride As Long
stride = ((width * 24 + 31) \ 32) * 4 ' 等價 ((width * 3 + 3) \ 4) * 4
' 讀取時按 stride 跳過填充
For y = 0 To height - 1
Dim rowPtr As Long = y * stride
For x = 0 To width - 1
Dim pixelPtr As Long = rowPtr + x * 3
' 讀取 BGR 三字節
Next
Next
bi.biWidth = width
bi.biHeight = -height ' 負值表示自上而下 (top-down),避免垂直翻轉
bi.biBitCount = 24
bi.biCompression = BI_RGB
bi.biSizeImage = stride * height ' 必須正確設定
BITMAPINFOHEADER,biWidth、biHeight (負值)、biBitCount=24、biSizeImage=stride*height。ReDim bits(stride * height - 1)。GetDIBits(hdc, hBmp, 0, height, bits(0), bi, DIB_RGB_COLORS)。offset = y * stride + x * 3。修正後橫座標從 (0,0) 開始正常遞增,無循環位移。