为什么这个位图操作代码要从步幅中减去宽度?

本文关键字:位图 操作 代码 为什么 | 更新日期: 2023-09-27 17:50:18

imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);行在下面的代码中是什么意思?

var width = bitmap.Width;
var height = bitmap.Width;
var horizontalProjection = new double[width];
var verticalProjection = new double[height];
var bitmapData1 = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        unsafe
        {
            var imagePointer1 = (byte*)bitmapData1.Scan0;
            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var blu = imagePointer1[0];
                    var green = imagePointer1[1];
                    var red = imagePointer1[2];
                    int luminosity = (byte)(((0.2126 * red) + (0.7152 * green)) + (0.0722 * blu));
                    horizontalProjection[x] += luminosity;
                    verticalProjection[y] += luminosity;
                    imagePointer1 += 4;
                } 
               imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
            }
        }
        MaximizeScale(ref horizontalProjection, height);
        MaximizeScale(ref verticalProjection, width);
        var projections = 
            new[]
                {
                    horizontalProjection, 
                    verticalProjection
                };
        bitmap.UnlockBits(bitmapData1);
        return projections;

为什么这个位图操作代码要从步幅中减去宽度?

代码只是增加了变量imagePointer1中包含的指针。

你必须增加stride - (width * 4)的原因是位图在内存中的表示方式。

Bob Powell的GDI+ FAQ中有一个非常全面的解释