开发者

Why would you subtract 1 from the Width and Height properties of a Bitmap?

I have the following code:

public static double[][] GetRgbProjections(Bitmap bitmap)
{
    var width = bitmap.Width - 1;
    var height = bitmap.Height - 1;

    var horizontalProjection = new double[width];
   开发者_JAVA百科 var verticalProjection = new double[height];

    var bitmapData1 = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

Does anyone know what the bitmap.Width - 1 is for? Also the bitmap.Height - 1;? Why would you subtract 1 from each of those property values?


The values returned by the Width and Height properties are exclusive, meaning that the pixel with the coordinates (Width, Height) lies immediately outside of the bounds of the bitmap.

Thus, if you want to iterate through the pixels, you need to subtract one to get the correct number of rows or columns.

Of course, it's hard to tell much more. The values aren't used again in the section of code you've shown.


No. We will never know what the purpose of subtracting 1 from the bitmap width because we do not know the context of bitmap.


The reason for this is to make the array indices match up with the row and height values of the bitmap. Consider:

You have a 2x2 pixel bitmap. It has 4 total pixels, 2 for both width and height. If you want to iterate through it, you need to iterate from 0 to 1 inclusive in both directions (width and height), but if you go by bitmap pixels, you will be iterating between 1 and 2 which will result in an index out of bounds.

Personally, I would have not subtracted one from the width and height variables, but only subtracted when iterating through the pixel array to prevent confusion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜