John Z. Li
John Z. Li

Reputation: 1995

Does the Bitmap class in C# store pixels column by column internally

Consider the following code sample, from msdn,

private void SetPixel_Example(PaintEventArgs e)
{
    // Create a Bitmap object from a file.
    Bitmap myBitmap = new Bitmap("Grapes.jpg");

    // Draw myBitmap to the screen.
    e.Graphics.DrawImage(myBitmap, 0, 0, myBitmap.Width, myBitmap.Height);

    // Set each pixel in myBitmap to black.
    for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
    {
        for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
        {
            myBitmap.SetPixel(Xcount, Ycount, Color.Black);
        }
    }

    // Draw myBitmap to the screen again.
    e.Graphics.DrawImage(myBitmap, myBitmap.Width, 0, myBitmap.Width, myBitmap.Height);
}

Note that the outer loop in the nest for loop iterates on indexes towards the bitmap's width, and the inner loop iterates on indexes towards the bitmap's height. I saw code snippets of the same style in several other places.

My question is: Does this mean that a Bitmap object stores its pixels information column by column internally, that is, thinking of all pixels as a matrix in the screen, it is stored in the main memory by column, as in programming language Fortran. The reasoning behind this question is to avoid cache miss, nested loop should be arranged according the memory format of a 2-D data structure.

Upvotes: 2

Views: 409

Answers (1)

Tatranskymedved
Tatranskymedved

Reputation: 4371

The source code of the Bitmap can be found here. Internally the bitmap details are stored in Image object (a reference to in-memory C++ object), which is part of GDI+.

What you've found on MSDN is an abstraction layer (as Adriano Repetti said), which allows you not to deal with the code behind. The thing is, if You want to work with such objects, You have to go through these "abstraction layers", which might decrease the performance. Other way around is to use some other library or program this Bitmap/Image object holders yourself.

Upvotes: 2

Related Questions