我制作了3x3的图像,所有方块都是黑色(0,0,0),除非角落...... 我有一个红色,绿色,蓝色和白色像素,如下图所示:
R, 0, G
0, 0, 0
B, 0, W
如果我理解正确的话,应该在pixeldata数组中放置R, 0, G, 0, 0, 0, B, 0, W
。
我遇到的问题是打印出来的是:
[255, 0, 0] [0, 0, 0] [0, 0, 0]
[0, 0, 0] [0, 0, 0] [0, 0, 0]
[0, 0, 255] [0, 0, 255] [255, 0, 0]
这是我的代码:
Uint32 GetPixel(SDL_Surface *img, int x, int y) {
//Convert the pixels to 32 bit
Uint32 *pixels = (Uint32*)img->pixels;
//Get the requested pixel
Uint32 offsetY = y * img->w;
Uint32 offsetPixel = offsetY + x;
Uint32 pixel = pixels[offsetPixel];
return pixel;
}
int main(int argc, char *argv[]) {
printf("Hello world!\n");
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Surface *img = IMG_Load("Images/Colors.png");
vector <Uint32> pixels;
SDL_LockSurface(img);
for (int y = 0; y < img->h; y++) {
Uint8 r, g, b;
Uint32 pixel;
for (int x = 0; x < img->w; x++) {
pixel = GetPixel(img, x, y);
SDL_GetRGB(pixel, img->format, &r, &g, &b);
printf("[%u, %u, %u]\t", r, g, b);
pixels.push_back(pixel);
}
printf("\n");
}
SDL_UnlockSurface(img);
system("pause");
return 0;
}
编辑:我的期望:
[255, 0, 0] [0, 0, 0] [0, 255, 0]
[0, 0, 0] [0, 0, 0] [0, 0, 0]
[0, 0, 255] [0, 0, 0] [255, 255, 255]
答案 0 :(得分:1)
问题出在您的GetPixel
功能范围内。尝试这样的事情:
Uint32 GetPixel(SDL_Surface *surface, int x, int y)
{
int bpp = surface->format->BytesPerPixel;
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
return *(Uint32*)p;
}