SDL2逐像素读取PNG24
SDL2 read PNG24 pixel by pixel
我有一个 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);
尝试从类型为 Uint8
的 *p
中提取值。它只有一个字节,所以是的——根据像素格式,它只会是红色或 alpha。 SDL_GetRGBA
期望 Uint32
,因此调用应该是例如SDL_GetRGBA(*(Uint32*)p, surface->format, &red, &green, &blue, &alpha);
(它只对 32bpp 格式有效 - 如果不是这种情况,您应该将表面转换为 32 位,或者 memcpy
BytesPerPixel
像素数据量,否则结果将不正确)
我有一个 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);
尝试从类型为 Uint8
的 *p
中提取值。它只有一个字节,所以是的——根据像素格式,它只会是红色或 alpha。 SDL_GetRGBA
期望 Uint32
,因此调用应该是例如SDL_GetRGBA(*(Uint32*)p, surface->format, &red, &green, &blue, &alpha);
(它只对 32bpp 格式有效 - 如果不是这种情况,您应该将表面转换为 32 位,或者 memcpy
BytesPerPixel
像素数据量,否则结果将不正确)