Porytiles
Loading...
Searching...
No Matches
png_indexed_image_loader.cpp
Go to the documentation of this file.
2
3#include <format>
4#include <vector>
5
6#include "png++/png.hpp"
7
11
12namespace porytiles {
13
14ChainableResult<std::unique_ptr<Image<IndexPixel>>>
15PngIndexedImageLoader::load_from_file(const std::filesystem::path &path) const
16{
17 if (!exists(path)) {
18 return FormattableError{std::format("file does not exist: {}", path.string())};
19 }
20
21 try {
22 // Do this here so if the source is not a PNG, we can catch and give a better error
23 png::image<png::index_pixel> test{path};
24 }
25 catch (std::exception &) {
26 return FormattableError{"'{}': File not a valid indexed PNG.", FormatParam{path.string(), Style::bold}};
27 }
28
29 png::image<png::index_pixel> png{path};
30 const auto tilesheet_width = png.get_width();
31 const auto tilesheet_height = png.get_height();
32 const auto tilesheet_size = tilesheet_width * tilesheet_height;
33
34 // Extract palette from PNG and convert to Rgba32
35 const auto &png_pal = png.get_palette();
36 std::vector<Rgba32> rgba_pal;
37 rgba_pal.reserve(png_pal.size());
38 for (const auto &color : png_pal) {
39 rgba_pal.emplace_back(color.red, color.green, color.blue, Rgba32::alpha_opaque);
40 }
41
42 auto image = std::make_unique<Image<IndexPixel>>(tilesheet_width, tilesheet_height, std::move(rgba_pal));
43 for (std::size_t pixel_index = 0; pixel_index < tilesheet_size; pixel_index++) {
44 const auto row = pixel_index / tilesheet_width;
45 const auto col = pixel_index % tilesheet_width;
46 image->set(pixel_index, IndexPixel{png[row][col]});
47 }
48
49 return image;
50}
51
52} // namespace porytiles
A text parameter with associated styling for formatted output.
General-purpose error implementation with formatted message support.
Definition error.hpp:63
Represents an indexed color pixel.
ChainableResult< std::unique_ptr< Image< IndexPixel > > > load_from_file(const std::filesystem::path &path) const
static constexpr std::uint8_t alpha_opaque
Definition rgba32.hpp:26
static const Style bold
Bold text formatting.