Loading Image from Disk        

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

// 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 = texture_path.find_last_of('.');
		if (index_of_extension != Ogre::String::npos)
		{
			tex_ext = texture_path.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.