gpt4 book ai didi

c++ - SDL2逐像素读取PNG24

转载 作者:行者123 更新时间:2023-11-28 06:01:11 24 4
gpt4 key购买 nike

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

关于c++ - SDL2逐像素读取PNG24,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com