How to find the average between RGB colors c1 and c2 in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>

std::string rgbToHex(int r, int g, int b) {
    std::ostringstream oss;
    oss << "#" 
        << std::uppercase << std::setfill('0') << std::hex
        << std::setw(2) << r
        << std::setw(2) << g
        << std::setw(2) << b;

    return oss.str();
}

int main() {
    // Color 1: RGB(255, 100, 50)
    int r1 = 255, g1 = 100, b1 = 50;

    // Color 2: RGB(50, 170, 200)
    int r2 = 50, g2 = 170, b2 = 200;

    // Average components
    int avgR = (r1 + r2) / 2;
    int avgG = (g1 + g2) / 2;
    int avgB = (b1 + b2) / 2;

    // Convert to hex string
    std::string hexColor = rgbToHex(avgR, avgG, avgB);
    std::cout << "Average Color (hex): " << hexColor << std::endl;
}



/*
run:

Average Color (hex): #98877D

*/

 



answered Jun 18, 2025 by avibootz

Related questions

...