MCPcopy Create free account
hub / github.com/OneLoneCoder/olcPixelGameEngine / LoadImageResource

Method LoadImageResource

olcPixelGameEngine.h:6563–6653  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6561 {}
6562
6563 olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override
6564 {
6565 UNUSED(pack);
6566
6567 // clear out existing sprite
6568 spr->pColData.clear();
6569
6570 ////////////////////////////////////////////////////////////////////////////
6571 // Use libpng, Thanks to Guillaume Cottenceau
6572 // https://gist.github.com/niw/5963798
6573 // Also reading png from streams
6574 // http://www.piko3d.net/tutorials/libpng-tutorial-loading-png-files-from-streams/
6575 png_structp png;
6576 png_infop info;
6577
6578 auto loadPNG = [&]()
6579 {
6580 png_read_info(png, info);
6581 png_byte color_type;
6582 png_byte bit_depth;
6583 png_bytep* row_pointers;
6584 spr->width = png_get_image_width(png, info);
6585 spr->height = png_get_image_height(png, info);
6586 color_type = png_get_color_type(png, info);
6587 bit_depth = png_get_bit_depth(png, info);
6588 if (bit_depth == 16) png_set_strip_16(png);
6589 if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
6590 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png);
6591 if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
6592 if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE)
6593 png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
6594 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6595 png_set_gray_to_rgb(png);
6596 png_read_update_info(png, info);
6597 row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * spr->height);
6598 for (int y = 0; y < spr->height; y++) {
6599 row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info));
6600 }
6601 png_read_image(png, row_pointers);
6602 ////////////////////////////////////////////////////////////////////////////
6603 // Create sprite array
6604 spr->pColData.resize(spr->width * spr->height);
6605 // Iterate through image rows, converting into sprite format
6606 for (int y = 0; y < spr->height; y++)
6607 {
6608 png_bytep row = row_pointers[y];
6609 for (int x = 0; x < spr->width; x++)
6610 {
6611 png_bytep px = &(row[x * 4]);
6612 spr->SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3]));
6613 }
6614 }
6615
6616 for (int y = 0; y < spr->height; y++) // Thanks maksym33
6617 free(row_pointers[y]);
6618 free(row_pointers);
6619 png_destroy_read_struct(&png, &info, nullptr);
6620 };

Callers

nothing calls this directly

Calls 5

PixelClass · 0.85
SetPixelMethod · 0.80
GetFileBufferMethod · 0.80
clearMethod · 0.45
resizeMethod · 0.45

Tested by

no test coverage detected