Add ImageWriter

This commit is contained in:
josh committed 2026-10-28 21:28:28 -04:00
1 parent 917bfe4821
commit a233b746c2
2 files changed
+61

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
#include <fart/ImageWriter.h>
#include <png.h>
#include <stdint.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <vector>
static uint8_t to_byte(double v)
{
return (uint8_t)std::lround(std::clamp(v, 0.0, 1.0) * 255.0);
}
static bool write_png(const Image & image, const std::string & fname)
{
std::vector<uint8_t> buffer(image.width * image.height * 4u);
for (size_t i = 0u; i < image.pixels.size(); i++)
{
const Color & c = image.pixels[i];
buffer[i * 4u + 0u] = to_byte(c.r);
buffer[i * 4u + 1u] = to_byte(c.g);
buffer[i * 4u + 2u] = to_byte(c.b);
buffer[i * 4u + 3u] = to_byte(c.a);
}
png_image png = {};
png.version = PNG_IMAGE_VERSION;
png.width = image.width;
png.height = image.height;
png.format = PNG_FORMAT_RGBA;
if (!png_image_write_to_file(&png, fname.c_str(), 0, buffer.data(), 0, nullptr))
{
fprintf(stderr, "Error writing PNG file '%s': %s\n", fname.c_str(), png.message);
png_image_free(&png);
return false;
}
return true;
}
bool ImageWriter::write(const Image & image, const std::string & fname)
{
std::string ext = std::filesystem::path(fname).extension().string();
if (ext == ".png")
{
return write_png(image, fname);
}
fprintf(stderr, "Unsupported output image format: '%s'\n", fname.c_str());
return false;
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <string>
#include <fart/Image.h>
class ImageWriter
{
public:
static bool write(const Image & image, const std::string & fname);
};