Porytiles
Loading...
Searching...
No Matches
png_indexed_image_loader.cpp
Go to the documentation of this file.
2
3#include <expected>
4
5#include "fmt/format.h"
6#include "png++/png.hpp"
7
10
11namespace porytiles2 {
12
13Result<std::unique_ptr<Image<IndexPixel>>>
14PngIndexedImageLoader::load_from_file(const std::filesystem::path &path) const
15{
16 if (!exists(path)) {
17 return std::unexpected{fmt::format("file does not exist: {}", path.string())};
18 }
19
20 try {
21 // Do this here so if the source is not a PNG, we can catch and give a better error
22 png::image<png::index_pixel> test{path};
23 }
24 catch (std::exception &) {
25 return std::unexpected{fmt::format("file not a valid indexed PNG: {}", path.string())};
26 }
27
28 png::image<png::index_pixel> tilesheet_png{path};
29 const auto tilesheet_width = tilesheet_png.get_width();
30 const auto tilesheet_height = tilesheet_png.get_height();
31 const auto tilesheet_size = tilesheet_width * tilesheet_height;
32 auto image = std::make_unique<Image<IndexPixel>>(tilesheet_width, tilesheet_height);
33 for (unsigned int pixel_index = 0; pixel_index < tilesheet_size; pixel_index++) {
34 const auto row = pixel_index / tilesheet_width;
35 const auto col = pixel_index % tilesheet_width;
36 // TODO: make sure this sets 4-bit pixels only, even if input tiles.png is using true-color (8-bit)
37 image->set(pixel_index, IndexPixel{tilesheet_png[row][col]});
38 }
39
40 return image;
41}
42
43} // namespace porytiles2
Represents an indexed color pixel.
Result< std::unique_ptr< Image< IndexPixel > > > load_from_file(const std::filesystem::path &path) const