How to access each byte in a bitmap image

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

    Use LockBits member on Bitmap class to obtain BitmapData, then use Scan0 and Marshal.ReadByte to readbytes. Here is small example (it is not about correct brightness adjustment, though):

        public static void AdjustBrightness(Bitmap image, int brightness)
        {
            int offset = 0;
            brightness = (brightness * 255) / 100;
            // GDI+ still lies to us - the return format is BGR, NOT RGB.
            BitmapData bmData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    
            int stride = bmData.Stride;
            IntPtr Scan0 = bmData.Scan0;
    
            int nVal = 0;
            int nOffset = stride - image.Width * 3;
            int nWidth = image.Width * 3;
    
            for (int y = 0; y < image.Height; ++y)
            {
                for (int x = 0; x < nWidth; ++x)
                {
                    nVal = Marshal.ReadByte(Scan0, offset) + brightness;
    
                    if (nVal < 0)
                        nVal = 0;
                    if (nVal > 255)
                        nVal = 255;
    
                    Marshal.WriteByte(Scan0, offset, (byte)nVal);
                    ++offset;
                }
                offset += nOffset;
            }
            image.UnlockBits(bmData);
        }
    

提交回复
热议问题