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 PngLoader::PngLoader(IO::Base &io, const string &sig):
37 priv->png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &priv->message, error, 0);
38 priv->info = png_create_info_struct(priv->png);
40 // These probably won't give any errors
41 png_set_read_fn(priv->png, &io, read);
42 png_set_sig_bytes(priv->png, sig.size());
45 PngLoader::~PngLoader()
47 png_destroy_read_struct(&priv->png, &priv->info, 0);
51 bool PngLoader::detect(const std::string &sig)
53 return !png_sig_cmp(reinterpret_cast<png_byte *>(const_cast<char*>(sig.data())), 0, sig.size());
56 void PngLoader::load(Image::Data &data)
58 if(setjmp(png_jmpbuf(priv->png)))
59 throw bad_image_data(priv->message);
61 png_read_info(priv->png, priv->info);
66 png_get_IHDR(priv->png, priv->info, &width, &height, &depth, &color, 0, 0, 0);
70 throw unsupported_image_format("depth!=8");
73 case PNG_COLOR_TYPE_PALETTE: data.fmt = COLOR_INDEX; break;
74 case PNG_COLOR_TYPE_GRAY: data.fmt = LUMINANCE; break;
75 case PNG_COLOR_TYPE_GRAY_ALPHA: data.fmt = LUMINANCE_ALPHA; break;
76 case PNG_COLOR_TYPE_RGB: data.fmt = RGB; break;
77 case PNG_COLOR_TYPE_RGB_ALPHA: data.fmt = RGBA; break;
78 default: throw unsupported_image_format("unknown color type");
81 unsigned nchans = png_get_channels(priv->png, priv->info);
82 if(nchans==4 && data.fmt==RGB)
83 png_set_strip_alpha(priv->png);
85 unsigned rowstride = data.width*nchans;
86 data.data = new char[rowstride*data.height];
87 for(unsigned y=0; y<data.height; ++y)
88 png_read_row(priv->png, reinterpret_cast<png_byte *>(data.data+rowstride*(data.height-1-y)), 0);
90 png_read_end(priv->png, 0);
93 } // namespace Graphics