c - SDL2 如何渲染原始格式的像素?

标签 c byte sdl render pixel

我正在尝试渲染自定义图像,它要求我将文件加载到内存中并通过 SDL 渲染出来。该图像是原始格式,我想我是否可以渲染

我的代码可能是垃圾,所以我愿意接受更改。

void Create_SDL_Window()
{

        SDL_Init(SDL_INIT_EVERYTHING);
        IMG_Init(IMG_INIT_PNG);
        window = SDL_CreateWindow("Test Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        renderer = SDL_CreateRenderer(window, -1, 0);
        printf("Window And Renderer Created!\n");
}






int main(){
FILE* customImage = fopen(Path, "rb");



Create_SDL_Window();

while (!quit){

        void *p;
        p = customImage;

        SDL_Texture* buffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_BGRA8888,SDL_TEXTUREACCESS_STREAMING, 800, 600);

        SDL_LockTexture(buffer, NULL, &p, &pitch);

        SDL_UnlockTexture(buffer);
        SDL_RenderCopy(renderer, buffer, NULL, NULL);


        SDL_RenderPresent(renderer);



while (SDL_PollEvent(&e)){
        //If user closes the window
        if (e.type == SDL_QUIT){
                quit = true;
        }
        //If user presses any key
        if (e.type == SDL_KEYDOWN){
        //      quit = true;
        }
        //If user clicks the mouse
        if (e.type == SDL_MOUSEBUTTONDOWN){
        ///     quit = true;
                }
        }

        SDL_RenderPresent(renderer);

}

最佳答案

你把事情搞反了。您应该注意到 SDL_LockTexture 采用一个指向指针的指针。这是因为 SDL 已经有一个适合纹理大小的缓冲区,并且它需要告诉您地址(和间距),以便您可以写入该缓冲区。

您还遇到一个问题,您认为可以使用 FILE* 作为像素缓冲区。这根本不是真的。 FILE* 是指向描述文件的结构的指针,而不是其内容。

您需要做的是:

// create your empty texture
...
int pitch = 0;
char* p = NULL;
SDL_LockTexture(buffer, NULL, &p, &pitch);
... // Error checking

// now open your file and mmap it
int fd = open(Path, O_RDONLY);
struct stat sb;
fstat(fd, &sb);

const char* memblock = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
... // Error checking

// now you need to copy the data from the file to the pixel buffer
// you claim you are working with 800x600 32bit image data

for (int y = 0; y < 600; ++y)
{
    const char* src = &memblock[y * pitch]; // is this really the pitch of the file? you didn't specify....
    char* dst = &p[y * pitch];
    memcpy(dst, src, 800*4); // width * size of a pixel
}

此代码假设您没有在其他地方犯错误,例如纹理的大小或像素的格式。您还会注意到需要找出的代码中的一些未知数。

您也可以尝试SDL_UpdateTexture,它将接受指向像素的指针,就像您在代码中尝试的那样。但是,它可能比 SDL_LockTexture 慢得多,并且您仍然需要实际读取文件(或者更好的是 mmap 它)来获取传入的像素。

如果 SDL_Image 知道如何读取“RAW”文件,第三种选择是使用 IMG_Load 获取 SDL_Surface然后使用 SDL_CreateTextureFromSurface

从该表面创建图像

关于c - SDL2 如何渲染原始格式的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395293/

相关文章:

c - 我试图在一个函数中初始化一个 SDL_Window,但它总是失败,除非我定义 SDL_Window*win;作为全局变量

c++ - 函数参数列表中的三个点是什么意思?

c - 如何关闭在外部函数中打开的文件

c# - C# 中的错误 "This stream does not support seek operations"

java - 字节类型行为不是预期的

char[] 到 uint32_t 无法正常工作

c++ - 对候选人进行排名的最佳、有效方法是什么

c - 使用直方图查找数组中最常见的字母

c++ - SDL_Mixer 是否可以在自身上播放单个 block ?

c++ - 尝试打开 SDL2 窗口时与 D-Bus 相关的运行时崩溃