1 #include "imageloader.h"
2 #include <msp/core/algorithm.h>
3 #include <msp/core/refptr.h>
4 #include <msp/io/file.h>
5 #include <msp/strings/format.h>
6 #include <msp/strings/utils.h>
9 #include "png/pngloader.h"
12 #include "jpeg/jpegloader.h"
15 #include "devil/devilloader.h"
18 #include "quartz/quartzloader.h"
26 ImageLoader::~ImageLoader()
31 bool ImageLoader::detect_signature(const string &sig)
33 Registry ®istry = get_registry();
34 for(const RegisterBase *r: registry.loaders)
40 ImageLoader *ImageLoader::open_file(const string &fn)
44 RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
45 ImageLoader *loader = open_io(*file);
46 loader->source = file.release();
49 catch(const unsupported_image_format &e)
51 throw unsupported_image_format(format("%s: %s", fn, e.what()));
55 ImageLoader *ImageLoader::open_io(IO::Seekable &io)
57 Registry ®istry = get_registry();
60 registry.changed = false;
61 sort(registry.loaders, [](RegisterBase *r1, RegisterBase *r2){
62 return r1->get_signature_size()<r2->get_signature_size();
66 if(registry.loaders.empty())
67 throw unsupported_image_format("no loaders");
69 string signature(registry.loaders.back()->get_signature_size(), 0);
70 unsigned sig_len = io.read(&signature[0], signature.size());
72 ImageLoader *loader = nullptr;
73 for(auto i=registry.loaders.begin(); (!loader && i!=registry.loaders.end()); ++i)
74 if((*i)->detect(signature))
75 loader = (*i)->create(io);
77 io.seek(0, IO::S_BEG);
82 for(unsigned i=0; i<sig_len; ++i)
83 append(sig_hex, " ", format("%02X", static_cast<unsigned char>(signature[i])));
84 throw unsupported_image_format(sig_hex);
90 void ImageLoader::load(Image::Data &data)
93 throw logic_error("already loaded");
95 if(state<HEADERS_LOADED)
98 data.pixels = data.owned_pixels = new char[data.stride*data.height];
103 void ImageLoader::load_headers(Image::Data &data)
105 if(state>=HEADERS_LOADED)
106 throw logic_error("headers already loaded");
109 state = HEADERS_LOADED;
112 ImageLoader::Registry &ImageLoader::get_registry()
114 static Registry registry;
115 static bool initialized = false;
119 register_loader<BmpLoader>();
121 register_loader<PngLoader>();
124 register_loader<JpegLoader>();
127 register_loader<DevilLoader>();
130 register_loader<QuartzLoader>();
137 ImageLoader::Registry::~Registry()
143 } // namespace Graphics