相关代码:
zip_stat_t filestat;
uint64_t filetotal = 0;
SDL_RWops* rwop = SDL_AllocRW();
//bunch of code that's not relevant to the matter goes here
std::vector<char> rwbuffer(filestat.size);
rwop = SDL_RWFromMem(rwbuffer.data(), filestat.size);
while(filetotal < filestat.size)
{
char buffer[256];
int64_t length;
//read the file into the buffer
length = zip_fread(file, buffer, 256);
if (length == -1)
{
u_error(std::cerr, CC_ERROR_ZIP, "zip_fread");
zip_fclose(file);
SDL_FreeRW(rwop);
return false;
}
//write the buffer into the rwop stream
if ( (uint16_t)length != SDL_RWwrite(rwop, buffer, 1, (size_t)length) )
{
u_error(std::cerr, CC_ERROR_SDL, "SDL_RWwrite");
zip_fclose(file);
SDL_FreeRW(rwop);
return false;
}
//Increment the count so that the loop ends
filetotal += length;
}
zip_fclose(file);
//Put it onto a surface
SDL_Surface* surf_load = IMG_Load_RW(rwop, 0);
if(surf_load == NULL)
{
u_error(std::cerr, CC_ERROR_IMAGE, "IMG_Load_RW");
SDL_FreeRW(rwop);
u_cleanup(surf_load);
return false;
}
//...
我已经用调试器转储了 vector rwbuffer的内容,它是有效的png,但是IMG_Load_RW仍然给我一个错误“不支持的图像格式”。我已经安装了libpng,并且IMG_Init似乎可以正常工作,因此SDL_image库必须可以正常工作。显然libzip给我正确的数据。我对为什么会出错感到非常困惑。
最佳答案
我想到了。在数据读取的while循环结束时,RWops流的查找值位于文件的末尾,而IMG_LoadPNG_RW不会将其重置,因此我必须手动SDL_RWseek(rwop,0,RW_SEEK_SET);在while循环完成之后,为了读取png数据。
//Return the seek pointer of the RWop to the beginning so that the file can be read
SDL_RWseek(rwop,0,RW_SEEK_SET);
//Put it onto a surface
SDL_Surface* surf_load = IMG_Load_RW(rwop, 0);
if(surf_load == NULL)
{
u_error(std::cerr, CC_ERROR_IMAGE, "IMG_Load_RW");
SDL_FreeRW(rwop);
u_cleanup(surf_load);
return false;
}
关于c++ - 在LibZip中使用SDL_image和SDL_RWops将zip中的png加载到表面上,但无法识别png,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61067536/