我有一个getpixel
函数,给定一个表面,读取给定像素的r,g,b和alpha值:
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;
}
我用Phosothop“Save for Web”保存了PNG图像,我选择了PNG24作为格式。问题是该函数只读取红色值,并始终将alpha读为0。 我试图强制这样的格式:
SDL_Surface* temp = IMG_Load(png_file_path.c_str());
SDL_Surface* image = SDL_ConvertSurfaceFormat(temp, SDL_PIXELFORMAT_RGBA8888, 0);
SDL_FreeSurface(temp);
通过这样做,它只读取alpha值。如何在SDL2中逐像素读取PNG?
答案 0 :(得分:1)
SDL_GetRGBA(*p, surface->format, &red, &green, &blue, &alpha);
尝试从*p
中提取值Uint8
的值。它只有一个字节,所以是的 - 根据像素格式,它只是红色或alpha。 SDL_GetRGBA
期待Uint32
,因此请致电SDL_GetRGBA(*(Uint32*)p, surface->format, &red, &green, &blue, &alpha);
(它仅适用于32bpp格式 - 如果不是这种情况,您应该将表面转换为32位,或者memcpy
BytesPerPixel
像素数据,否则结果不正确)