简体   繁体   中英

SDL2 read PNG24 pixel by pixel

I have a getpixel function that, given a surface, reads the r, g, b and alpha value of a given pixel:

void getpixel(SDL_Surface *surface, int x, int y) {
    int bpp = surface->format->BytesPerPixel;
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    Uint8 red, green, blue, alpha;

    SDL_GetRGBA(*p, surface->format, &red, &green, &blue, &alpha);

    cout << (int)red << " " << (int)green << " " << (int)blue << " " << (int)alpha  << endl;

}

I saved a PNG image with Phosothop "Save for Web" and I choose PNG24 as format. The problem is that the function only reads the red value and always read alpha as 0. I tried to force the format like so:

SDL_Surface* temp  = IMG_Load(png_file_path.c_str()); 
SDL_Surface* image =  SDL_ConvertSurfaceFormat(temp, SDL_PIXELFORMAT_RGBA8888, 0);
SDL_FreeSurface(temp);

By doing so it only read the alpha value, instead. How to read a PNG pixel by pixel in SDL2?

SDL_GetRGBA(*p, surface->format, &red, &green, &blue, &alpha); attempts to extract values from *p , which have type Uint8 . It is only one byte, so yes - it would be only red or alpha depending on pixel format. SDL_GetRGBA expects Uint32 , so call should be eg SDL_GetRGBA(*(Uint32*)p, surface->format, &red, &green, &blue, &alpha);

(it would only be valid for 32bpp formats - if it isn't the case, you should either convert surface to 32 bit, or or memcpy BytesPerPixel amount of pixel data, otherwise results will be incorrect)

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