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 char *buf, unsigned len)
36 return !png_sig_cmp(reinterpret_cast<png_byte *>(const_cast<char*>(buf)), 0, len);
39 void load_png(IO::Base &in, Image::Private &priv, const char *, unsigned sig_len)
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_set_sig_bytes(png, sig_len);
56 png_read_info(png, info);
61 png_get_IHDR(png, info, &width, &height, &depth, &color, 0, 0, 0);
65 throw unsupported_image_format("depth!=8");
68 case PNG_COLOR_TYPE_PALETTE: priv.fmt = COLOR_INDEX; break;
69 case PNG_COLOR_TYPE_GRAY: priv.fmt = LUMINANCE; break;
70 case PNG_COLOR_TYPE_GRAY_ALPHA: priv.fmt = LUMINANCE_ALPHA; break;
71 case PNG_COLOR_TYPE_RGB: priv.fmt = RGB; break;
72 case PNG_COLOR_TYPE_RGB_ALPHA: priv.fmt = RGBA; break;
73 default: throw unsupported_image_format("unknown color type");
76 unsigned nchans = png_get_channels(png, info);
77 if(nchans==4 && priv.fmt==RGB)
78 png_set_strip_alpha(png);
80 unsigned rowstride = priv.width*nchans;
81 priv.data = new char[rowstride*priv.height];
82 for(unsigned y=0; y<priv.height; ++y)
83 png_read_row(png, reinterpret_cast<png_byte *>(priv.data+rowstride*(priv.height-1-y)), 0);
86 png_destroy_read_struct(&png, &info, 0);
90 png_destroy_read_struct(&png, &info, 0);
96 } // namespace Graphics