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
35 PngLoader::PngLoader(IO::Base &io, unsigned sig_bytes):
38 priv->png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &priv->message, error, 0);
39 priv->info = png_create_info_struct(priv->png);
41 // These probably won't give any errors
42 png_set_read_fn(priv->png, &io, read);
43 png_set_sig_bytes(priv->png, sig_bytes);
46 PngLoader::~PngLoader()
48 png_destroy_read_struct(&priv->png, &priv->info, 0);
52 bool PngLoader::detect(const std::string &sig)
54 return !png_sig_cmp(reinterpret_cast<png_byte *>(const_cast<char*>(sig.data())), 0, sig.size());
57 void PngLoader::load(Image::Data &data)
61 if(setjmp(png_jmpbuf(priv->png)))
64 throw bad_image_data(priv->message);
67 png_read_info(priv->png, priv->info);
73 png_get_IHDR(priv->png, priv->info, &width, &height, &depth, &color, &interlace, 0, 0);
74 unsigned nchans = png_get_channels(priv->png, priv->info);
77 throw unsupported_image_format("depth!=8");
81 data.stride = data.width*nchans;
85 case PNG_COLOR_TYPE_PALETTE: data.fmt = COLOR_INDEX; break;
86 case PNG_COLOR_TYPE_GRAY: data.fmt = LUMINANCE; break;
87 case PNG_COLOR_TYPE_GRAY_ALPHA: data.fmt = LUMINANCE_ALPHA; break;
88 case PNG_COLOR_TYPE_RGB: data.fmt = (nchans==4 ? RGBX : RGB); break;
89 case PNG_COLOR_TYPE_RGB_ALPHA: data.fmt = RGBA; break;
90 default: throw unsupported_image_format("unknown color type");
93 data.data = new char[data.stride*data.height];
95 if(interlace==PNG_INTERLACE_ADAM7)
97 // ADAM7 requires all rows to be loaded at once
98 unsigned n_passes = png_set_interlace_handling(priv->png);
99 rows = new png_byte *[data.height];
100 for(unsigned y=0; y<data.height; ++y)
101 rows[y] = reinterpret_cast<png_byte *>(data.data+data.stride*(data.height-1-y));
103 for(unsigned i=0; i<n_passes; ++i)
104 png_read_rows(priv->png, rows, 0, data.height);
111 for(unsigned y=0; y<data.height; ++y)
112 png_read_row(priv->png, reinterpret_cast<png_byte *>(data.data+data.stride*(data.height-1-y)), 0);
115 png_read_end(priv->png, 0);
118 } // namespace Graphics