Porytiles
Loading...
Searching...
No Matches
png_rgba_image_loader.cpp
Go to the documentation of this file.
2
3#include <filesystem>
4#include <memory>
5#include <string>
6
7#include "CImg.h"
8
11
12namespace porytiles2 {
13
14using cimg_library::CImg;
15using cimg_library::CImgException;
16
17ChainableResult<std::unique_ptr<Image<Rgba32>>, ImageLoadError>
18PngRgbaImageLoader::load_from_file(const std::filesystem::path &path) const
19{
20 using enum ImageLoadError::Type;
21
22 if (!exists(path)) {
23 return ImageLoadError::file_not_found(path.string());
24 }
25
26 CImg<std::uint8_t> cimg_png{};
27 const auto path_c_str = path.c_str();
28 try {
29 cimg_png.assign(path_c_str);
30 }
31 catch (const CImgException &e) {
32 return ImageLoadError::other_load_error(path.string(), e.what());
33 }
34
35 if (cimg_png.spectrum() != 3 && cimg_png.spectrum() != 4) {
36 return ImageLoadError::unsupported_channel_count(path.string(), cimg_png.spectrum());
37 }
38
39 const auto width = static_cast<std::size_t>(cimg_png.width());
40 const auto height = static_cast<std::size_t>(cimg_png.height());
41
42 Image<Rgba32> image{width, height};
43
44 for (std::size_t row = 0; row < height; ++row) {
45 for (std::size_t col = 0; col < width; ++col) {
46 const auto red = cimg_png(col, row, 0, 0);
47 const auto green = cimg_png(col, row, 0, 1);
48 const auto blue = cimg_png(col, row, 0, 2);
49
50 // PNGs with no alpha channel are considered opaque
51 const auto alpha = (cimg_png.spectrum() == 3) ? Rgba32::alpha_opaque : cimg_png(col, row, 0, 3);
52
53 image.set(row, col, Rgba32{red, green, blue, alpha});
54 }
55 }
56
57 return std::make_unique<Image<Rgba32>>(std::move(image));
58}
59
60} // namespace porytiles2
A template for two-dimensional images with arbitrarily typed pixel values.
Definition image.hpp:24
ChainableResult< std::unique_ptr< Image< Rgba32 > >, ImageLoadError > load_from_file(const std::filesystem::path &path) const
Represents a 32-bit RGBA color.
Definition rgba32.hpp:21
static constexpr std::uint8_t alpha_opaque
Definition rgba32.hpp:24
@ blue
Blue text color.
@ green
Green text color.
@ red
Red text color.