Porytiles
Loading...
Searching...
No Matches
png_rgba_image_saver.cpp
Go to the documentation of this file.
2
3#include <expected>
4#include <filesystem>
5#include <string>
6
7#include "CImg.h"
8#include "fmt/format.h"
9
13
14namespace porytiles2 {
15
16using cimg_library::CImg;
17using cimg_library::CImgException;
18
19ChainableResult<void>
20PngRgbaImageSaver::save_to_file(const Image<Rgba32> &image, const std::filesystem::path &path) const
21{
22 const auto width = static_cast<int>(image.width());
23 const auto height = static_cast<int>(image.height());
24 constexpr auto spectrum = 4; // RGBA
25
26 // Cannot use braced initializer here, it confuses the compiler
27 CImg<std::uint8_t> cimg_png(width, height, 1, spectrum);
28
29 for (std::size_t row = 0; row < image.height(); ++row) {
30 for (std::size_t col = 0; col < image.width(); ++col) {
31 const auto pixel = image.at(row, col);
32
33 cimg_png(col, row, 0, 0) = pixel.red();
34 cimg_png(col, row, 0, 1) = pixel.green();
35 cimg_png(col, row, 0, 2) = pixel.blue();
36 cimg_png(col, row, 0, 3) = pixel.alpha();
37 }
38 }
39
40 const auto path_c_str = path.c_str();
41 try {
42 std::ignore = cimg_png.save_png(path_c_str);
43 }
44 catch (const std::exception &e) {
45 return FormattableError{fmt::format("{}: save failed: {}", path.filename().c_str(), e.what())};
46 }
47
48 return {};
49}
50
51} // namespace porytiles2
General-purpose error implementation with formatted message support.
Definition error.hpp:117
A template for two-dimensional images with arbitrarily typed pixel values.
Definition image.hpp:24
std::size_t width() const
Gets the width of this image in pixels.
Definition image.hpp:108
PixelType at(std::size_t i) const
Fetches the pixel value at a given one-dimensional pixel index.
Definition image.hpp:45
std::size_t height() const
Gets the height of this image in pixels.
Definition image.hpp:118
virtual ChainableResult< void > save_to_file(const Image< Rgba32 > &image, const std::filesystem::path &path) const