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, signature_size_compare);
64 if(registry.loaders.empty())
65 throw unsupported_image_format("no loaders");
67 string signature(registry.loaders.back()->get_signature_size(), 0);
68 unsigned sig_len = io.read(&signature[0], signature.size());
70 ImageLoader *loader = nullptr;
71 for(auto i=registry.loaders.begin(); (!loader && i!=registry.loaders.end()); ++i)
72 if((*i)->detect(signature))
73 loader = (*i)->create(io);
75 io.seek(0, IO::S_BEG);
80 for(unsigned i=0; i<sig_len; ++i)
81 append(sig_hex, " ", format("%02X", static_cast<unsigned char>(signature[i])));
82 throw unsupported_image_format(sig_hex);
88 void ImageLoader::load(Image::Data &data)
91 throw logic_error("already loaded");
93 if(state<HEADERS_LOADED)
96 data.pixels = data.owned_pixels = new char[data.stride*data.height];
101 void ImageLoader::load_headers(Image::Data &data)
103 if(state>=HEADERS_LOADED)
104 throw logic_error("headers already loaded");
107 state = HEADERS_LOADED;
110 ImageLoader::Registry &ImageLoader::get_registry()
112 static Registry registry;
113 static bool initialized = false;
117 register_loader<BmpLoader>();
119 register_loader<PngLoader>();
122 register_loader<JpegLoader>();
125 register_loader<DevilLoader>();
128 register_loader<QuartzLoader>();
134 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
136 return r1->get_signature_size()<r2->get_signature_size();
140 ImageLoader::Registry::~Registry()
146 } // namespace Graphics