Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void ReadPng(const std::string& filename) {
- FILE* fp = fopen(filename.c_str(), "rb");
- if (!fp) {
- throw std::runtime_error("Can't open file " + filename);
- }
- png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
- if (!png) {
- throw std::runtime_error("Can't create png read struct");
- }
- png_infop info = png_create_info_struct(png);
- if (!info) {
- throw std::runtime_error("Can't create png info struct");
- }
- if (setjmp(png_jmpbuf(png))) {
- abort();
- }
- png_init_io(png, fp);
- png_read_info(png, info);
- width_ = png_get_image_width(png, info);
- height_ = png_get_image_height(png, info);
- png_byte color_type = png_get_color_type(png, info);
- png_byte bit_depth = png_get_bit_depth(png, info);
- // Read any color_type into 8bit depth, RGBA format.
- // See http://www.libpng.org/pub/png/libpng-manual.txt
- if (bit_depth == 16) {
- png_set_strip_16(png);
- }
- if (color_type == PNG_COLOR_TYPE_PALETTE) {
- png_set_palette_to_rgb(png);
- }
- // PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth.
- if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
- png_set_expand_gray_1_2_4_to_8(png);
- }
- if (png_get_valid(png, info, PNG_INFO_tRNS)) {
- png_set_tRNS_to_alpha(png);
- }
- // These color_type don't have an alpha channel then fill it with 0xff.
- if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY ||
- color_type == PNG_COLOR_TYPE_PALETTE) {
- png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
- }
- if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
- png_set_gray_to_rgb(png);
- }
- png_read_update_info(png, info);
- bytes_ = static_cast<png_bytep*>(malloc(sizeof(png_bytep) * height_));
- for (int y = 0; y < height_; y++) {
- bytes_[y] = static_cast<png_byte*>(malloc(png_get_rowbytes(png, info)));
- }
- png_read_image(png, bytes_);
- png_destroy_read_struct(&png, &info, nullptr);
- fclose(fp);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement