Search code examples
c++pixelsdl-image

Getting incorrect readings from image


I have made a image of 3x3 with all squares black (0,0,0) unless the corners... Where I have a red, green, blue and white pixel, as illustrated below:

R, 0, G
0, 0, 0
B, 0, W

Which should be placed as R, 0, G, 0, 0, 0, B, 0, W in the pixeldata array if I understood it correctly. The problem I'm having is that what is printed out is:

[255, 0, 0] [0, 0, 0]   [0, 0, 0]
[0, 0, 0]   [0, 0, 0]   [0, 0, 0]
[0, 0, 255] [0, 0, 255] [255, 0, 0]

Here is my code:

Uint32 GetPixel(SDL_Surface *img, int x, int y) {
    //Convert the pixels to 32 bit
    Uint32 *pixels = (Uint32*)img->pixels;

    //Get the requested pixel
    Uint32 offsetY = y * img->w;
    Uint32 offsetPixel = offsetY + x;
    Uint32 pixel = pixels[offsetPixel];

    return pixel;
}



int main(int argc, char *argv[]) {
    printf("Hello world!\n");

    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *img = IMG_Load("Images/Colors.png");
    vector <Uint32> pixels;

    SDL_LockSurface(img);

    for (int y = 0; y < img->h; y++) {
        Uint8 r, g, b;
        Uint32 pixel;
        for (int x = 0; x < img->w; x++) {
            pixel = GetPixel(img, x, y);

            SDL_GetRGB(pixel, img->format, &r, &g, &b);
            printf("[%u, %u, %u]\t", r, g, b);
            pixels.push_back(pixel);
        }
        printf("\n");
    }

    SDL_UnlockSurface(img);

system("pause");
return 0;
}

EDIT: What I expected:

[255, 0, 0] [0, 0, 0]   [0, 255, 0]
[0, 0, 0]   [0, 0, 0]   [0, 0, 0]
[0, 0, 255] [0, 0, 0]   [255, 255, 255]

Solution

  • The problem is within your GetPixel function. Try something like this instead:

    Uint32 GetPixel(SDL_Surface *surface, int x, int y)
    {
        int bpp = surface->format->BytesPerPixel;
        Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
        return *(Uint32*)p;
    }