1 #include "imageloader.h"
2 #include <msp/core/refptr.h>
3 #include <msp/io/file.h>
4 #include <msp/strings/format.h>
5 #include <msp/strings/utils.h>
8 #include "png/pngloader.h"
11 #include "jpeg/jpegloader.h"
14 #include "devil/devilloader.h"
17 #include "quartz/quartzloader.h"
25 ImageLoader::~ImageLoader()
30 bool ImageLoader::detect_signature(const string &sig)
32 Registry ®istry = get_registry();
33 for(const RegisterBase *r: registry.loaders)
39 ImageLoader *ImageLoader::open_file(const string &fn)
43 RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
44 ImageLoader *loader = open_io(*file);
45 loader->source = file.release();
48 catch(const unsupported_image_format &e)
50 throw unsupported_image_format(format("%s: %s", fn, e.what()));
54 ImageLoader *ImageLoader::open_io(IO::Seekable &io)
56 Registry ®istry = get_registry();
59 registry.changed = false;
60 registry.loaders.sort(signature_size_compare);
63 if(registry.loaders.empty())
64 throw unsupported_image_format("no loaders");
66 string signature(registry.loaders.back()->get_signature_size(), 0);
67 unsigned sig_len = io.read(&signature[0], signature.size());
69 ImageLoader *loader = 0;
70 for(auto i=registry.loaders.begin(); (!loader && i!=registry.loaders.end()); ++i)
71 if((*i)->detect(signature))
72 loader = (*i)->create(io);
74 io.seek(0, IO::S_BEG);
79 for(unsigned i=0; i<sig_len; ++i)
80 append(sig_hex, " ", format("%02X", static_cast<unsigned char>(signature[i])));
81 throw unsupported_image_format(sig_hex);
87 void ImageLoader::load(Image::Data &data)
90 throw logic_error("already loaded");
92 if(state<HEADERS_LOADED)
95 data.pixels = data.owned_pixels = new char[data.stride*data.height];
100 void ImageLoader::load_headers(Image::Data &data)
102 if(state>=HEADERS_LOADED)
103 throw logic_error("headers already loaded");
106 state = HEADERS_LOADED;
109 ImageLoader::Registry &ImageLoader::get_registry()
111 static Registry registry;
112 static bool initialized = false;
116 register_loader<BmpLoader>();
118 register_loader<PngLoader>();
121 register_loader<JpegLoader>();
124 register_loader<DevilLoader>();
127 register_loader<QuartzLoader>();
133 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
135 return r1->get_signature_size()<r2->get_signature_size();
139 ImageLoader::Registry::~Registry()
145 } // namespace Graphics