简体   繁体   中英

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];
    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.

不。我们永远不会知道从位图宽度减去1的目的是什么,因为我们不知道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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM