How to access each byte in a bitmap image

后端 未结 4 2031
暖寄归人
暖寄归人 2021-01-03 10:26

Say I have a bitmap image, is it possible to iterate through all the individual bytes in the image? If yes, how?

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 11:08

    Another solution is to use LockBits and Marshal.Copy to convert your bitmap into an array. I needed this solution because I had two images that differed only in their color depth and the other proffered solutions don't handle that well (or are too slow).

    using (Bitmap bmp = new Bitmap(fname)) {
        // Convert image to int32 array with each int being one pixel
        int cnt = bmp.Width * bmp.Height * 4 / 4;
        BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                                ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        Int32[] rgbValues = new Int32[cnt];
    
        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(bmData.Scan0, rgbValues, 0, cnt);
        bmp.UnlockBits(bmData);
        for (int i = 0; i < cnt; ++i) {
            if (rgbValues[i] == 0xFFFF0000)
                Console.WriteLine ("Red byte");
        }
    }
    

提交回复
热议问题