4 #include "image_private.h"
15 void read(png_struct *png, png_byte *data, png_size_t size)
17 Msp::IO::Base *in = reinterpret_cast<Msp::IO::Base *>(png_get_io_ptr(png));
18 in->read(reinterpret_cast<char *>(data), size);
21 void error(png_struct *png, const char *msg)
23 ErrorInfo *error_info = reinterpret_cast<ErrorInfo *>(png_get_error_ptr(png));
24 error_info->msg = msg;
25 longjmp(png_jmpbuf(png), 1);
34 bool is_png(const void *buf, unsigned len)
36 return !png_sig_cmp(reinterpret_cast<png_byte *>(const_cast<void *>(buf)), 0, len);
39 void load_png(IO::Base &in, Image::Private &priv)
48 png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &error_info, error, 0);
49 info = png_create_info_struct(png);
51 if(setjmp(png_jmpbuf(png)))
52 throw bad_image_data(error_info.msg);
54 png_set_read_fn(png, &in, read);
55 png_read_info(png, info);
60 png_get_IHDR(png, info, &width, &height, &depth, &color, 0, 0, 0);
64 throw unsupported_image_format("depth!=8");
67 case PNG_COLOR_TYPE_PALETTE: priv.fmt = COLOR_INDEX; break;
68 case PNG_COLOR_TYPE_GRAY: priv.fmt = LUMINANCE; break;
69 case PNG_COLOR_TYPE_GRAY_ALPHA: priv.fmt = LUMINANCE_ALPHA; break;
70 case PNG_COLOR_TYPE_RGB: priv.fmt = RGB; break;
71 case PNG_COLOR_TYPE_RGB_ALPHA: priv.fmt = RGBA; break;
72 default: throw unsupported_image_format("unknown color type");
75 unsigned nchans = png_get_channels(png, info);
76 if(nchans==4 && priv.fmt==RGB)
77 png_set_strip_alpha(png);
79 unsigned rowstride = priv.width*nchans;
80 priv.data = new char[rowstride*priv.height];
81 for(unsigned y=0; y<priv.height; ++y)
82 png_read_row(png, reinterpret_cast<png_byte *>(priv.data+rowstride*(priv.height-1-y)), 0);
85 png_destroy_read_struct(&png, &info, 0);
89 png_destroy_read_struct(&png, &info, 0);
95 } // namespace Graphics