這是我在 VB.NET 將全彩色減色運算到 256 色的部份程式碼:
….
bitmapData = bitmap.LockBits(rect, Drawing.Imaging.ImageLockMode.WriteOnly, Drawing.Imaging.PixelFormat.Format8bppIndexed)
Dim pixels As IntPtr = bitmapData.Scan0
Dim pBits As Int32
Dim bits As Byte()
If (bitmapData.Stride > 0) Then
pBits = pixels.ToInt32()
Else
pBits = pixels.ToInt32() + bitmapData.Stride * (Height – 1)
End If
Dim stride As Integer = Math.Abs(bitmapData.Stride)
ReDim bits(Height * stride)
Dim row, col As Integer
Dim arrBitmapArray As Integer() = GetBitmapIntegerArray(BmpCopy)
Dim ipp As Integer
Dim pixel As ColorDim i8BppPixel As Integer
Dim luminance, colorIndex As Double
For ipp = 0 To UBound(arrBitmapArray)
pixel = Color.FromArgb(arrBitmapArray(ipp))
luminance = (pixel.R * 0.299) + (pixel.G * 0.587) + (pixel.B * 0.114)
colorIndex = Math.Round((luminance * (nColors – 1) / 255))
bits(ipp) = CByte(colorIndex)
Next
CopyMemory(pBits, bits, Height * stride)
bitmap.UnlockBits(bitmapData)
….
Public Function GetBitmapIntegerArray(ByVal oBitmap As Object) As Integer()
Dim nLen = oBitmap.Width * oBitmap.Height
Dim hBitmap As IntPtr = oBitmap.GetHbitmap()
Dim arrBmpArray(nLen – 1) As Integer
Dim summy As Integer = GetBitmapBits(hBitmap, 4 * nLen, arrBmpArray)
DeleteObject(hBitmap)
Return arrBmpArray
End Function
如果只要 GetPixel ,可以直接:
GetBitmapIntegerArray
配上 CopyMemory 也可以轉為 2D 的陣列。
有興趣的可以參考那篇的討論,那篇發問者要問 c# ,所以他有把他的 c# 原始碼改好後放上討論區。