SDL2逐像素读取PNG24

SDL2 read PNG24 pixel by pixel

本文关键字:PNG24 读取 像素 SDL2      更新时间:2023-10-16

我有一个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 ?

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格式有效-如果不是这种情况,您应该将surface转换为32位,或者memcpyBytesPerPixel的像素数据量,否则结果将不正确)