在我的C++应用程序中,我有一个png图像的颜色,红色,绿色,蓝色值.我已将这些值存储在三个整数中.
如何将RGB值转换为等效的十六进制值?
这种格式的例子就像0x1906一样
编辑:我将格式保存为GLuint.
Nik*_* C. 19
将每种颜色的相应位存储为至少24位的无符号整数(如a long):
unsigned long createRGB(int r, int g, int b)
{
return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}
Run Code Online (Sandbox Code Playgroud)
而不是:
unsigned long rgb = 0xFA09CA;
Run Code Online (Sandbox Code Playgroud)
你可以做:
unsigned long rgb = createRGB(0xFA, 0x09, 0xCA);
Run Code Online (Sandbox Code Playgroud)
请注意,上述内容不会处理alpha通道.如果你还需要编码alpha(RGBA),那么你需要这个:
unsigned long createRGBA(int r, int g, int b, int a)
{
return ((r & 0xff) << 24) + ((g & 0xff) << 16) + ((b & 0xff) << 8)
+ (a & 0xff);
}
Run Code Online (Sandbox Code Playgroud)
更换unsigned long用GLuint如果这就是你所需要的.
如果要构建字符串,可以使用snprintf():
const unsigned red = 0, green = 0x19, blue = 0x06;
char hexcol[16];
snprintf(hexcol, sizeof hexcol, "%02x%02x%02x", red, green, blue);
Run Code Online (Sandbox Code Playgroud)
这将构建字符串001906" inhexcol`,这就是我选择解释你的示例颜色(当它应该是6时只有四位数).
您似乎对GL_ALPHA预处理器符号定义为0x1906OpenGL的头文件这一事实感到困惑.这不是一种颜色,它是与处理像素的OpenGL API调用一起使用的格式说明符,因此它们知道期望的格式.
如果你在内存中有一个PNG图像,GL_ALPHA格式只对应于图像中的alpha值(如果存在),上面的内容完全不同,因为它构建了一个字符串.OpenGL不需要字符串,它需要一个内存缓冲区来保存所需格式的数据.
有关其glTexImage2D()工作原理的讨论,请参见手册页.