00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00024
00026
00028 #include <SFML/Graphics/ImageLoader.hpp>
00029 #include <iostream>
00030 #undef _UNICODE
00031 #include <IL/il.h>
00032
00033
00034 namespace sf
00035 {
00036 namespace priv
00037 {
00041 ImageLoader& ImageLoader::GetInstance()
00042 {
00043 static ImageLoader Instance;
00044
00045 return Instance;
00046 }
00047
00048
00052 ImageLoader::ImageLoader()
00053 {
00054
00055 ilInit();
00056 ILenum ErrorCode = ilGetError();
00057 if (ErrorCode != IL_NO_ERROR)
00058 {
00059 std::cerr << "Failed to initialize DevIL library (error code : " << ErrorCode << ")" << std::endl;
00060 return;
00061 }
00062
00063
00064 ILint ILVersion = ilGetInteger(IL_VERSION_NUM);
00065 if (ILVersion < IL_VERSION)
00066 {
00067 std::cerr << "DevIL library has incorrect version (is " << ILVersion << ", should be " << IL_VERSION << ")" << std::endl;
00068 return;
00069 }
00070
00071
00072 ilEnable(IL_FILE_OVERWRITE);
00073
00074
00075 ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
00076 ilEnable(IL_ORIGIN_SET);
00077
00078
00079 ilSetInteger(IL_FORMAT_MODE, IL_RGBA);
00080 ilEnable(IL_FORMAT_SET);
00081 }
00082
00083
00087 ImageLoader::~ImageLoader()
00088 {
00089
00090 ilShutDown();
00091 }
00092
00093
00097 bool ImageLoader::LoadImageFromFile(const std::string& Filename, std::vector<Uint32>& Pixels, unsigned int& Width, unsigned int& Height)
00098 {
00099
00100 ILuint Image;
00101 ilGenImages(1, &Image);
00102 ilBindImage(Image);
00103
00104
00105 if (ilLoadImage(const_cast<char*>(Filename.c_str())) == false)
00106 {
00107 std::cerr << "Failed to load image from file \"" << Filename << "\"" << std::endl;
00108 ilDeleteImages(1, &Image);
00109 return false;
00110 }
00111
00112
00113 Width = ilGetInteger(IL_IMAGE_WIDTH);
00114 Height = ilGetInteger(IL_IMAGE_HEIGHT);
00115
00116
00117 const Uint32* PixelsPtr = reinterpret_cast<const Uint32*>(ilGetData());
00118 Pixels.assign(PixelsPtr, PixelsPtr + Width * Height);
00119
00120
00121 ilDeleteImages(1, &Image);
00122
00123 return true;
00124 }
00125
00126
00130 bool ImageLoader::SaveImageToFile(const std::string& Filename, const std::vector<Uint32>& Pixels, unsigned int Width, unsigned int Height)
00131 {
00132
00133 ILuint Image;
00134 ilGenImages(1, &Image);
00135 ilBindImage(Image);
00136
00137
00138 if (!ilTexImage(Width, Height, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, const_cast<Uint32*>(&Pixels[0])))
00139 {
00140 std::cerr << "Failed to save image to file \"" << Filename << "\"" << std::endl;
00141 ilDeleteImages(1, &Image);
00142 return false;
00143 }
00144
00145
00146 if (!ilSaveImage(const_cast<char*>(Filename.c_str())))
00147 {
00148 std::cerr << "Failed to save image to file \"" << Filename << "\"" << std::endl;
00149 ilDeleteImages(1, &Image);
00150 return false;
00151 }
00152
00153
00154 ilDeleteImages(1, &Image);
00155
00156 return true;
00157 }
00158
00159 }
00160
00161 }