texproc/image.cpp
2025-01-19 19:50:30 +01:00

45 lines
1.2 KiB
C++

#include "image.hpp"
#include <stb_image.h>
#include <stb_image_write.h>
#include <stdexcept>
Image::Image(const std::string& path) {
int width, height, channels;
stbi_uc* data = stbi_load(path.c_str(), &width, &height, &channels, 4);
if (!data) {
throw std::runtime_error("Failed to load image: " + path);
}
m_width = width;
m_height = height;
m_data = std::make_unique<ColorRGBA[]>(m_width * m_height);
for (size_t y = 0; y < m_height; y++) {
for (size_t x = 0; x < m_width; x++) {
size_t idx_dst = y * m_width + x;
size_t idx_src = idx_dst * 4;
ColorRGBA& pixel = m_data[idx_dst];
pixel.rgb.r = data[idx_src + 0];
pixel.rgb.g = data[idx_src + 1];
pixel.rgb.b = data[idx_src + 2];
pixel.a = data[idx_src + 3];
}
}
stbi_image_free(data);
}
Image::Image(size_t width, size_t height) {
m_width = width;
m_height = height;
m_data = std::make_unique<ColorRGBA[]>(m_width * m_height);
}
void Image::Save(const std::string& path) const {
stbi_write_png(path.c_str(), m_width, m_height, 4, m_data.get(), m_width * 4);
}