从十六进制字符串颜色到RGB颜色

时间:2014-03-19 14:15:23

标签: c++ colors hex rgb

如何将hexadecimal字符串颜色#FF0022值转换为RGB中的C++颜色?

发件人:

#FF0022

r:255
g:0
b:34

我不知道该怎么做,我搜索谷歌没有运气,请告诉我如何做到这一点,以便我可以了解更多。

2 个答案:

答案 0 :(得分:3)

解析字符串,然后使用strtol()将每组两个字符转换为十进制。

答案 1 :(得分:0)

以下是代码示例:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

std::vector<std::string> SplitWithCharacters(const std::string& str, int splitLength) {
  int NumSubstrings = str.length() / splitLength;
  std::vector<std::string> ret;

  for (int i = 0; i < NumSubstrings; i++) {
     ret.push_back(str.substr(i * splitLength, splitLength));
  }

  // If there are leftover characters, create a shorter item at the end.
  if (str.length() % splitLength != 0) {
      ret.push_back(str.substr(splitLength * NumSubstrings));
  }


  return ret;
}

struct COLOR {
  short r;
  short g;
  short b;
};

COLOR hex2rgb(string hex) {
  COLOR color;

  if(hex.at(0) == '#') {
      hex.erase(0, 1);
  }

  while(hex.length() != 6) {
      hex += "0";
  }

  std::vector<string> colori=SplitWithCharacters(hex,2);

  color.r = stoi(colori[0],nullptr,16);
  color.g = stoi(colori[1],nullptr,16);
  color.b = stoi(colori[2],nullptr,16);

  return color;
}

int main() {
  string hexcolor;

  cout << "Insert hex color: ";
  cin >> hexcolor;

  COLOR color = hex2rgb(hexcolor);

  cout << "RGB:" << endl;
  cout << "R: " << color.r << endl;
  cout << "G: " << color.g << endl;
  cout << "B: " << color.b << endl;

  return 0;
}