Skip to content

Image Converter — C++ source

Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.

This is the C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Image converter — C++ port of the image-converter tool.

#include <memory>
#include <stdexcept>
#include <string>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

enum class Format { png, jpeg };

class Image {
public:
    Image(const std::string& path) {
        data_.reset(stbi_load(path.c_str(), &w_, &h_, &n_, 4));
        if (!data_) throw std::runtime_error("decode failed");
    }

    // JPEG has no alpha channel: composite every pixel over opaque white,
    // or transparency renders black in the encoded file.
    void flattenOntoWhite() {
        for (int i = 0; i < w_ * h_ * 4; i += 4) {
            unsigned a = data_[i + 3];
            for (int c = 0; c < 3; c++)
                data_[i + c] = static_cast<unsigned char>(
                    (data_[i + c] * a + 255u * (255u - a) + 127u) / 255u);
            data_[i + 3] = 255;
        }
    }

    // quality is 1..100 (the web tool's 0..1 slider times 100).
    void save(const std::string& path, Format fmt, int quality) const {
        bool ok = fmt == Format::jpeg
                      ? stbi_write_jpg(path.c_str(), w_, h_, 4, data_.get(), quality)
                      : stbi_write_png(path.c_str(), w_, h_, 4, data_.get(), w_ * 4);
        if (!ok) throw std::runtime_error("encode failed");
    }

private:
    std::unique_ptr<unsigned char, void (*)(void*)> data_{nullptr, &stbi_image_free};
    int w_ = 0, h_ = 0, n_ = 0;
};

int main(int argc, char** argv) {
    if (argc != 4) return 1;
    try {
        Image img{argv[1]};
        bool jpeg = std::string{argv[2]}.find(".jp") != std::string::npos;
        if (jpeg) img.flattenOntoWhite();
        img.save(argv[2], jpeg ? Format::jpeg : Format::png, std::stoi(argv[3]));
    } catch (const std::exception& e) {
        return 1;
    }
    return 0;
}

Also available in 8 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →