Skip to main content

Some times it is necessary to store a image from the current render target (e.g. your Ogre::RenderWindow) to an Image.
This is a short Snippets, that describs the way for Qt.

Copy to clipboard
QImage getImageFromRenderTarget(Ogre::RenderTarget* render_target) const { if(render_target == 0) return QImage(); Ogre::DataStreamPtr image_data_stream; QImage image_render_view; try { // create PixelBox and get data from target Ogre::PixelFormat pf = render_target->suggestPixelFormat(); unsigned int target_width = render_target->getWidth(); unsigned int target_height = render_target->getHeight(); size_t bp_box_size = target_width * target_height * Ogre::PixelUtil::getNumElemBytes(pf); unsigned char* ogre_pixel_data = new unsigned char[bp_box_size]; Ogre::PixelBox pixelbox(target_width, target_height, 1, pf, ogre_pixel_data); render_target->copyContentsToMemory(pixelbox); // load data into Ogre::Image and encode to bmp Ogre::Image ogre_image = Ogre::Image().loadDynamicImage(ogre_pixel_data, target_width, target_height, 1, pf); image_data_stream = ogre_image.encode("bmp"); // get size and data from Ogre::Image size_t bmp_buffer_size = size_t image_data_stream->size(); unsigned char* bmp_data = new unsigned char[bmp_buffer_size]; image_data_stream->read(bmp_data, bmp_buffer_size); //save data into QImage as BMP image_render_view = image_render_view.fromData(bmp_data, bmp_buffer_size, "BMP"); delete[] bmp_data; delete[] ogre_pixel_data; } catch(Ogre::Exception& ex) { std::stringstream error; error << "Could not read FrameBuffer Image: Error Description: " << ex.getFullDescription() << std::ends; // post the error to whatever you prefer return QImage(); } catch(...) { std::stringstream error; error << "An unknown error occured in getImageFromRenderTarget(Ogre::RenderTarget* render_target)" << std::ends; // post the error to whatever you prefer } return image_render_view; }