#include <iostream>
using namespace std;
const int M = 2000, N = 1200;
struct Color24 {
unsigned char R, G, B;
Color24() {
R = 0;
G = 0;
B = 0;
}
Color24(int r, int g, int b) : R((unsigned char) r), G((unsigned char) g), B((unsigned char) b) {}
bool operator==(const Color24 &rhs) const {
return R == rhs.R &&
G == rhs.G &&
B == rhs.B;
}
bool operator!=(const Color24 &rhs) const {
return !(rhs == *this);
}
void SetColor(string htmlColor) {
switch (htmlColor.size()) {
case 7: /// #010203
sscanf(("0x" + htmlColor.substr(1, 2)).c_str(), "%x", &R);
sscanf(("0x" + htmlColor.substr(3, 2)).c_str(), "%x", &G);
sscanf(("0x" + htmlColor.substr(5, 2)).c_str(), "%x", &B);
break;
case 4: /// #123
sscanf(("0x" + string(2, htmlColor[1])).c_str(), "%x", &R);
sscanf(("0x" + string(2, htmlColor[2])).c_str(), "%x", &G);
sscanf(("0x" + string(2, htmlColor[3])).c_str(), "%x", &B);
break;
case 2: /// #1
sscanf(("0x" + string(2, htmlColor[1])).c_str(), "%x", &R);
sscanf(("0x" + string(2, htmlColor[1])).c_str(), "%x", &G);
sscanf(("0x" + string(2, htmlColor[1])).c_str(), "%x", &B);
break;
default:
cout << "ERROR!!!Color convert: unexpect html type" << endl;
}
}
} Image[M * N];
string color2Format(Color24 color) {
char formatString[100];
sprintf(formatString, "\033[48;2;%d;%d;%dm", color.R, color.G, color.B);
return formatString;
}
int w, h;
int pixel_w, pixel_h;
Color24 getMeanColor(int row, int col) {
int R = 0, G = 0, B = 0;
int count = pixel_w * pixel_h;
int startX = col * pixel_w, startY = row * pixel_h;
for (int i = 0; i < pixel_h; ++i) {
for (int j = 0; j < pixel_w; ++j) {
R += Image[(i + startY) * w + (j + startX)].R;
G += Image[(i + startY) * w + (j + startX)].G;
B += Image[(i + startY) * w + (j + startX)].B;
}
}
return {R / count, G / count, B / count};
}
void convertToASCII(string raw) {
for (char c: raw) {
printf("\\x%.2X", c);
}
}
int main() {
cin >> w >> h;
cin >> pixel_w >> pixel_h;
string colorStr;
/// input image
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
cin >> colorStr;
Image[row * w + col].SetColor(colorStr);
}
}
string finalStr = "";
/// solve color setting
Color24 preColor;
for (int row = 0; row < h / pixel_h; ++row) {
for (int col = 0; col < w / pixel_w; ++col) {
Color24 meanColor = getMeanColor(row, col);
if (meanColor == preColor) {
finalStr += " ";
} else {
if (meanColor == Color24()) {
finalStr += "\033[0m ";
} else {
finalStr += color2Format(meanColor) + " ";
}
preColor = meanColor;
}
}
if (preColor != Color24())
finalStr += "\033[0m";
finalStr += "\n";
preColor = Color24();
}
// printf("%s", finalStr.c_str());
convertToASCII(finalStr);
/*printf("\\x%.2X \\x%.2X \\x%.2X", color.R, color.G, color.B);
char output[10]{};
itoa((int) color.R, output, 16);*/
return 0;
}
对象写的,我现在还在debug中,掉了太多的坑了。因为转化的原因