8 void read(png_struct *png, png_byte *data, png_size_t size)
10 Msp::IO::Base *in = reinterpret_cast<Msp::IO::Base *>(png_get_io_ptr(png));
11 in->read(reinterpret_cast<char *>(data), size);
14 void error(png_struct *png, const char *msg)
16 string *message = reinterpret_cast<string *>(png_get_error_ptr(png));
18 longjmp(png_jmpbuf(png), 1);
27 struct PngLoader::Private
34 ImageLoader::Register<PngLoader> PngLoader::reg;
36 PngLoader::PngLoader(IO::Base &io, unsigned sig_bytes):
39 priv->png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &priv->message, error, 0);
40 priv->info = png_create_info_struct(priv->png);
42 // These probably won't give any errors
43 png_set_read_fn(priv->png, &io, read);
44 png_set_sig_bytes(priv->png, sig_bytes);
47 PngLoader::~PngLoader()
49 png_destroy_read_struct(&priv->png, &priv->info, 0);
53 bool PngLoader::detect(const std::string &sig)
55 return !png_sig_cmp(reinterpret_cast<png_byte *>(const_cast<char*>(sig.data())), 0, sig.size());
58 void PngLoader::load(Image::Data &data)
60 if(setjmp(png_jmpbuf(priv->png)))
61 throw bad_image_data(priv->message);
63 png_read_info(priv->png, priv->info);
68 png_get_IHDR(priv->png, priv->info, &width, &height, &depth, &color, 0, 0, 0);
69 unsigned nchans = png_get_channels(priv->png, priv->info);
72 throw unsupported_image_format("depth!=8");
76 data.stride = data.width*nchans;
80 case PNG_COLOR_TYPE_PALETTE: data.fmt = COLOR_INDEX; break;
81 case PNG_COLOR_TYPE_GRAY: data.fmt = LUMINANCE; break;
82 case PNG_COLOR_TYPE_GRAY_ALPHA: data.fmt = LUMINANCE_ALPHA; break;
83 case PNG_COLOR_TYPE_RGB: data.fmt = (nchans==4 ? RGBX : RGB); break;
84 case PNG_COLOR_TYPE_RGB_ALPHA: data.fmt = RGBA; break;
85 default: throw unsupported_image_format("unknown color type");
88 data.data = new char[data.stride*data.height];
89 for(unsigned y=0; y<data.height; ++y)
90 png_read_row(priv->png, reinterpret_cast<png_byte *>(data.data+data.stride*(data.height-1-y)), 0);
92 png_read_end(priv->png, 0);
95 } // namespace Graphics