1 #include <msp/core/refptr.h>
2 #include <msp/io/file.h>
3 #include <msp/strings/format.h>
4 #include <msp/strings/utils.h>
6 #include "imageloader.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 ImageLoader::~ImageLoader()
35 ImageLoader *ImageLoader::open_file(const string &fn)
39 RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
40 ImageLoader *loader = open_io(*file);
41 loader->source = file.release();
44 catch(const unsupported_image_format &e)
46 throw unsupported_image_format(format("%s: %s", fn, e.what()));
50 ImageLoader *ImageLoader::open_io(IO::Seekable &io)
52 Registry ®istry = get_registry();
55 registry.changed = false;
56 registry.loaders.sort(signature_size_compare);
59 if(registry.loaders.empty())
60 throw unsupported_image_format("no loaders");
62 vector<char> sig_buf(registry.loaders.back()->get_signature_size());
63 unsigned sig_len = io.read(&sig_buf[0], sig_buf.size());
64 string signature(sig_buf.begin(), sig_buf.end());
66 ImageLoader *loader = 0;
67 for(list<RegisterBase *>::const_iterator i=registry.loaders.begin(); (!loader && i!=registry.loaders.end()); ++i)
68 if((*i)->detect(signature))
69 loader = (*i)->create(io);
71 io.seek(0, IO::S_BEG);
76 for(unsigned i=0; i<sig_len; ++i)
77 append(sig_hex, " ", format("%02X", static_cast<unsigned char>(sig_buf[i])));
78 throw unsupported_image_format(sig_hex);
84 void ImageLoader::load(Image::Data &data)
87 throw logic_error("already loaded");
89 if(state<HEADERS_LOADED)
92 data.pixels = data.owned_pixels = new char[data.stride*data.height];
97 void ImageLoader::load_headers(Image::Data &data)
99 if(state>=HEADERS_LOADED)
100 throw logic_error("headers already loaded");
103 state = HEADERS_LOADED;
106 ImageLoader::Registry &ImageLoader::get_registry()
108 static Registry registry;
109 static bool initialized = false;
113 register_loader<BmpLoader>();
115 register_loader<PngLoader>();
118 register_loader<JpegLoader>();
121 register_loader<DevilLoader>();
124 register_loader<QuartzLoader>();
130 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
132 return r1->get_signature_size()<r2->get_signature_size();
136 ImageLoader::Registry::Registry():
140 ImageLoader::Registry::~Registry()
142 for(list<RegisterBase *>::iterator i=loaders.begin(); i!=loaders.end(); ++i)
146 } // namespace Graphics