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

时间:2011-04-17 06:51:42

标签: c# .net bitmap

以下代码中的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;

1 个答案:

答案 0 :(得分:3)

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

你必须按步幅增加的原因 - (宽度* 4)是因为位图在内存中的表示方式。

作为Bob Powell's GDI+ FAQ的一部分,有一个非常全面的解释。