RenderTexture saveToFile returns true, but never writes the file

RenderTexture saveToFile returns true, but never writes the file

Using 3.8, I have this sequence:

	auto renderTexture = RenderTexture::create(PICSIZE.width, PICSIZE.height, PIXELFORMAT);
	renderTexture->begin();

	Sprite* spriteSource = Sprite::create(temppicfilename);
	if (!spriteSource) {
		CCLOGERROR("ERROR - failed loading sprite from path: %s", temppicfilename.c_str());
		return;
	}

	const Size SOURCESIZE = spriteSource->getContentSize();
	CCLOG("SOURCESIZE of picture: %f %f", SOURCESIZE.width, SOURCESIZE.height);
	const float NEWSCALE = PICSIZE.width / SOURCESIZE.width;

	CCLOG("SCALING: Use scale %f", NEWSCALE);
	spriteSource->setScale(NEWSCALE);

	const Point P = Point(PICSIZE.width * 0.5, PICSIZE.height * 0.5);
	CCLOG("P of spriteSource: %f x %f", P.x, P.y);
	spriteSource->setPosition(P);

	spriteSource->visit();
	renderTexture->end();

	std::string picfilename = writablepath + SceneGame::filenameOfPicanswer(pic.picid);
	const bool ISRGBA = true;
	CCLOG("Trying to save to %s", picfilename.c_str());

	const bool SAVESTATUS = renderTexture->saveToFile(picfilename, Image::Format::PNG, ISRGBA, [](RenderTexture* t, std::string s) {
		CCLOG("Saved resized texture done? %s", s.c_str());
	});
	CCLOG("SAVESTATUS: %d (%s)", SAVESTATUS, picfilename.c_str());

	if (!SAVESTATUS) {
		CCLOGERROR("ERROR Failed saving render texture to %s", picfilename.c_str());
		return;
	}
	else {
		//				* Notes: since v3.x, saveToFile will generate a custum command, which will be called in the following render->render().
		//				* So if this function is called in a event handler, the actual save file will be called in the next frame. If we switch to a different scene, the game will crash.
		//     * To solve this, add Director::getInstance()->getRenderer()->render(); after this function.
		Director::getInstance()->getRenderer()->render();
		CCLOG("Saved render texture to %s", picfilename.c_str());
		// Try to load the image just to see if that works?
		Sprite* spriteTest = Sprite::create(picfilename);
		if (spriteTest == NULL) {
			CCLOGERROR("ERROR: Picture NOT FOUND at %s although should be saved!", picfilename.c_str());
			return;
		}
	}

The sanity check to load the image from file after it has been written fails, so “ERROR: Picture NOT FOUND …” is always written. There is no file on disk.

I’ve trying to debug this for the last hour, with no fix so far.

Found my problem. saveToFile does NOT take absolute/full path. It should just be “somefile.png”… :joy:

2 Likes