Using Gdiplus to get pixel value of an image

3.2k Views Asked by At

This is quite a simple thing, but I am not really trained in C++. I just need to get each pixel value of an image. Let us say that it is "C:\LM3S811\red.bmp", 169x104 pixel.

By googling around the topic, I am convinced that gdiplus from Microsoft SDK should be able to do this. Below is my code to get red value of each pixel:

    #include <iostream>
    #include <windows.h>
    #include <gdiplus.h>
    using namespace Gdiplus;
    using namespace std;
    #pragma comment (lib, "Gdiplus.lib")

    int main(){

        // set bitmap to "C:\LM3S811\red.bmp"
        Bitmap myBitmap (L"C:\\LM3S811\\red.bmp");

        Color pixelColor;

        // print red value of each pixel of 169x104 pixel
        for (int y = 1; y <= 104; y++){
            for (int x = 1; x <= 169; x++){
                myBitmap.GetPixel(x, y, &pixelColor);
                cout << (int)pixelColor.GetRed() << ",";
            }
        }

        // end
        cout << endl;
        system("PAUSE");
        return 0;
    }

When I run the code, it always gives zero for all pixels. If I deliberately set pixelColor by doing i.e. Color pixelColor(0, 255, 255, 255); instead, then it will give the correct value 255. Seems myBitmap.GetPixel(x, y, &pixelColor); does not return pixelColor correctly. Please let me know the mistake of the code above.

Your help is really appreciated. Thanks!

1

There are 1 best solutions below

0
On

your for loops should start with 0 ... like this:

for (int y = 0; y < myBitmap.GetHeight(); y++){
    for (int x = 0; x < mybitmap.GetWidth(); x++){

otherwise your code looks ok to me ... maybe there's something wrong with your bitmap? tried another one? maybe a jpeg?