1. 程式人生 > >將二值圖像存入二值數組

將二值圖像存入二值數組

spa stride epo als pan for span .get eight

因項目需要,需要用一個將二值圖像保存在二維數組中的算法,在網上找了很久都沒找到,只能自己動手寫了。

        #region 讀取二值圖像存入二值數組

        public byte[,] BinaryBitmapToBinaryArray(Bitmap bmp)
        {
            int imgWidth = bmp.Width;
            int imgHeight = bmp.Height;

            byte[,] BinaryArray = new byte[imgHeight, imgWidth];
            
for (int i = 0; i < BinaryArray.GetLength(0); i++) { for (int j = 0; j < BinaryArray.GetLength(1); j++) { BinaryArray[i, j] = 1; } } int depth = Bitmap.GetPixelFormatSize(bmp.PixelFormat);
if (depth == 1) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat); int imgStride = bmpData.Stride; //得到首地址 IntPtr ptr = bmpData.Scan0;
//定義被鎖定的數組大小,由位圖數據與未用空間組成的 int bytes = imgStride * imgHeight; //定義位圖數組 byte[] bmpValues = new byte[bytes]; //復制被鎖定的位圖像素值到該數組內 Marshal.Copy(ptr, bmpValues, 0, bytes); int basePos = 0; bool isOne = false; for (int y = 0; y < imgHeight; y++) { basePos = y * imgStride; for (int x = 0; x < imgWidth; x ++) { isOne = ByteGetBit(bmpValues[basePos + (x >> 3)], (7-x & 0x7)); //ByteGetBit判斷一個字節第幾位是否是1,該函數是從後往前數的,而這裏是從高位向低位數的。所以要用7減去x & 0x7 if (isOne) { BinaryArray[y, x] = 255; } else { BinaryArray[y, x] = 0; } } } bmp.UnlockBits(bmpData); } return BinaryArray; } #endregion

將二值圖像存入二值數組