Advertisement
mrlantan

Untitled

Aug 25th, 2021
3,514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | None | 0 0
  1. void ReadPng(const std::string& filename) {
  2.         FILE* fp = fopen(filename.c_str(), "rb");
  3.         if (!fp) {
  4.             throw std::runtime_error("Can't open file " + filename);
  5.         }
  6.  
  7.         png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  8.         if (!png) {
  9.             throw std::runtime_error("Can't create png read struct");
  10.         }
  11.  
  12.         png_infop info = png_create_info_struct(png);
  13.         if (!info) {
  14.             throw std::runtime_error("Can't create png info struct");
  15.         }
  16.         if (setjmp(png_jmpbuf(png))) {
  17.             abort();
  18.         }
  19.  
  20.         png_init_io(png, fp);
  21.  
  22.         png_read_info(png, info);
  23.  
  24.         width_ = png_get_image_width(png, info);
  25.         height_ = png_get_image_height(png, info);
  26.         png_byte color_type = png_get_color_type(png, info);
  27.         png_byte bit_depth = png_get_bit_depth(png, info);
  28.  
  29.         // Read any color_type into 8bit depth, RGBA format.
  30.         // See http://www.libpng.org/pub/png/libpng-manual.txt
  31.  
  32.         if (bit_depth == 16) {
  33.             png_set_strip_16(png);
  34.         }
  35.  
  36.         if (color_type == PNG_COLOR_TYPE_PALETTE) {
  37.             png_set_palette_to_rgb(png);
  38.         }
  39.  
  40.         // PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth.
  41.         if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
  42.             png_set_expand_gray_1_2_4_to_8(png);
  43.         }
  44.  
  45.         if (png_get_valid(png, info, PNG_INFO_tRNS)) {
  46.             png_set_tRNS_to_alpha(png);
  47.         }
  48.  
  49.         // These color_type don't have an alpha channel then fill it with 0xff.
  50.         if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY ||
  51.             color_type == PNG_COLOR_TYPE_PALETTE) {
  52.             png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
  53.         }
  54.  
  55.         if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
  56.             png_set_gray_to_rgb(png);
  57.         }
  58.  
  59.         png_read_update_info(png, info);
  60.  
  61.         bytes_ = static_cast<png_bytep*>(malloc(sizeof(png_bytep) * height_));
  62.         for (int y = 0; y < height_; y++) {
  63.             bytes_[y] = static_cast<png_byte*>(malloc(png_get_rowbytes(png, info)));
  64.         }
  65.  
  66.         png_read_image(png, bytes_);
  67.         png_destroy_read_struct(&png, &info, nullptr);
  68.         fclose(fp);
  69.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement