How to access each byte in a bitmap image

后端 未结 4 1999
暖寄归人
暖寄归人 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:18

    If you need to access the pixel information, the super-slow but super-easy way is to call the GetPixel and SetPixel methods on your Bitmap object.

    The super-fast and not-that-hard way is to call the Bitmap's LockBits method and use the BitmapData object returned from it to read and write the Bitmap's byte data directly. You can do this latter part with the Marshal class as in Ilya's example, or you can skip the Marshal overhead like this:

        BitmapData data;
        int x = 0; //or whatever
        int y = 0;
        unsafe
        {
            byte* row = (byte*)data.Scan0 + (y * data.Stride);
            int columnOffset = x * 4;
            byte B = row[columnOffset];
            byte G = row[columnOffset + 1];
            byte R = row[columnOffset + 2];
            byte A = row[columnOffset + 3];
        }
    

提交回复
热议问题