Reputation: 58903
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?
Upvotes: 1
Views: 626
Reputation: 18399
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 e.g. 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)
Upvotes: 3