Bitmap.Lockbits confusion

后端 未结 1 694
北恋
北恋 2020-12-18 03:16

MSDN reference: [1] http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx#Y1178

From the link it says that the first argument will \"specifies the portion of the Bit

相关标签:
1条回答
  • 2020-12-18 03:37

    The stride will always be of the full bitmap, but the Scan0 property will be different according to the start point of the lock rectangle, as well as the Height and Width of the BitmapData.

    The reason for that is that you will still need to know the real bit-width of the bitmap, in order to iterate over the rows (add stride to address).

    A simple way to go about it would be:

    var bitmap = new Bitmap(100, 100);
    
    var data = bitmap.LockBits(new Rectangle(0, 0, 10, 10),
                               ImageLockMode.ReadWrite,
                               bitmap.PixelFormat);
    
    var pt = (byte*)data.Scan0;
    var bpp = data.Stride / bitmap.Width;
    
    for (var y = 0; y < data.Height; y++)
    {
        // This is why real scan-width is important to have!
        var row = pt + (y * data.Stride);
    
        for (var x = 0; x < data.Width; x++)
        {
            var pixel = row + x * bpp;
    
            for (var bit = 0; bit < bpp; bit++)
            {
                var pixelComponent = pixel[bit];
            }
        }
    }
    
    bitmap.UnlockBits(data);
    

    So it is basically really just locking the whole bitmap, but giving you a pointer to the top-left pixel of the rectangle in the bitmap, and setting the scan's width and height appropriately.

    0 讨论(0)
提交回复
热议问题