【问题标题】:SDL2 read PNG24 pixel by pixelSDL2逐像素读取PNG24
【发布时间】:2015-10-21 15:17:53
【问题描述】:

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

【问题讨论】:

  • 24 位不是意味着 3 个颜色分量(每个分量 8 位)吗?所以不会有 alpha 通道可以读取...

标签: c++ sdl-2


【解决方案1】:

SDL_GetRGBA(*p, surface-&gt;format, &amp;red, &amp;green, &amp;blue, &amp;alpha); 尝试从*p 中提取值,这些值的类型为Uint8。它只有一个字节,所以是的 - 根据像素格式,它只会是红色或 alpha。 SDL_GetRGBA 期望 Uint32,所以调用应该是例如SDL_GetRGBA(*(Uint32*)p, surface-&gt;format, &amp;red, &amp;green, &amp;blue, &amp;alpha);

(它只对 32bpp 格式有效 - 如果不是这种情况,您应该将表面转换为 32 位,或 memcpy BytesPerPixel 像素数据量,否则结果将不正确)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多