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
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_headers_(Image::Data &data)
60 if(setjmp(png_jmpbuf(priv->png)))
62 throw bad_image_data(priv->message);
65 png_read_info(priv->png, priv->info);
70 png_get_IHDR(priv->png, priv->info, &width, &height, &depth, &color, &priv->interlace, 0, 0);
71 unsigned nchans = png_get_channels(priv->png, priv->info);
74 throw unsupported_image_format("depth!=8");
78 data.stride = data.width*nchans;
82 case PNG_COLOR_TYPE_PALETTE: data.fmt = COLOR_INDEX; break;
83 case PNG_COLOR_TYPE_GRAY: data.fmt = LUMINANCE; break;
84 case PNG_COLOR_TYPE_GRAY_ALPHA: data.fmt = LUMINANCE_ALPHA; break;
85 case PNG_COLOR_TYPE_RGB: data.fmt = (nchans==4 ? RGBX : RGB); break;
86 case PNG_COLOR_TYPE_RGB_ALPHA: data.fmt = RGBA; break;
87 default: throw unsupported_image_format("unknown color type");
91 void PngLoader::load_pixels_(Image::Data &data)
95 if(setjmp(png_jmpbuf(priv->png)))
98 throw bad_image_data(priv->message);
101 if(priv->interlace==PNG_INTERLACE_ADAM7)
103 // ADAM7 requires all rows to be loaded at once
104 unsigned n_passes = png_set_interlace_handling(priv->png);
105 rows = new png_byte *[data.height];
106 for(unsigned y=0; y<data.height; ++y)
107 rows[y] = reinterpret_cast<png_byte *>(data.pixels+data.stride*(data.height-1-y));
109 for(unsigned i=0; i<n_passes; ++i)
110 png_read_rows(priv->png, rows, 0, data.height);
117 for(unsigned y=0; y<data.height; ++y)
118 png_read_row(priv->png, reinterpret_cast<png_byte *>(data.pixels+data.stride*(data.height-1-y)), 0);
121 png_read_end(priv->png, 0);
124 } // namespace Graphics