Skip to main content

History: Loading Image from Disk

Preview of version: 1

Introduction

There might be situations for programmers where an arbitrary image should be loaded into Ogre from the disk rather than from one of the resource locations. This code snippet helps loading the image into Ogre::TextureManager so that the programmer can then use the texture name to create material in runtime to display the image from the disk.

Code

Copy to clipboard
// Preprocessors required // #include <OgreResourceGroupManager.h> // #include <OgreTextureManager.h> // #include <OgreImage.h> // #include <OgreDataStream.h> // #include <fstream> bool LoadImage(const Ogre::String& texture_name, const Ogre::String& texture_path) { bool image_loaded = false; std::ifstream ifs(texture_path.c_str(), std::ios::binary|std::ios::in); if (ifs.is_open()) { Ogre::String tex_ext; Ogre::String::size_type index_of_extension = file_name.find_last_of('.'); if (index_of_extension != Ogre::String::npos) { tex_ext = file_name.substr(index_of_extension+1); Ogre::DataStreamPtr data_stream(new Ogre::FileStreamDataStream(texture_path, &ifs, false)); Ogre::Image img; img.load(data_stream, tex_ext); Ogre::TextureManager::getSingleton().loadImage(texture_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, img, Ogre::TEX_TYPE_2D, 0, 1.0f); image_loaded = true; } ifs.close(); } return image_loaded; }


NOTE: This code assumes the following:

  1. The user has verified that the file exists. If it doesn't then the funciton returns false.
  2. The user has made sure that a unique texture name is passed into the function
  3. The user is loading a 2D image.

History

Information Version
Fri 10 of Sep, 2010 09:30 GMT-0000 nikolaj_sheller Fixed minor compile problem by replacing "file_name" with "texture_path". I assume this was the author's intention. 2
Fri 20 of Aug, 2010 12:40 GMT-0000 Vitefalcon 1