本文主要是介绍CImage 设置任意像素的RGB值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当我们读取了CImage图像后,如果想要快速修改CImage所有像素的RGB值,应该怎么实现呢?
方法一:调用CImage的内部函数GetPixel(),GetRValue(),SetPixel()。缺点是调用函数需要入栈出栈的操作,消耗时间过长,比如一个5000*5000像素的图片,对所有像素点进行RGB设置需要等待好久。代码如下:
CImage image;
HRESULT hr = image.Load(file_name);
int image_height = image.GetHeight();
int image_width = image.GetWidth();
int r = 0, g = 0, b = 0;
COLORREF color;
for (int i = 0; i < image_width; i++){
for (int j = 0; j < image_height; j++){
color = image.GetPixel(i, j); //get pixel data from image
r = GetRValue(color); //get R value from color
g = GetGValue(color); //get G value from color
b = GetBValue(color); //get B value from color
image.SetPixel(i, j, RGB(r, g, b));/*设置一帧图像的像素值用来显示*/
}
}
方法二:直接修改像素点对应的地址,效率较高,代码如下:
CImage image;
HRESULT hr = image.Load(file_name);
int image_pitch = image.GetPitch();
int image_height = image.GetHeight();
int image_width = image.GetWidth();
byte* pSourceData;
pSourceData = (byte*)image.GetBits();
int image_bpp = image.GetBPP();
int r = 0, g = 0, b = 0, alpha = 0;
int gray = 0;
for (int i = 0; i < image_width; i++){
for (int j = 0; j < image_height; j++){
if (image_bpp == 8){
gray = *(pSourceData + j * image_pitch + i);
//进行灰度值设置
*(pSourceData + j * image_pitch + i) = 125;
}
if (image_bpp == 24){
r = *(pSourceData + j * image_pitch + i * 3);
g = *(pSourceData + j * image_pitch + i * 3 + 1);
b = *(pSourceData + j * image_pitch + i * 3 + 2);
//进行RGB设置
*(pSourceData + j * image_pitch + i * 3) = 175;//R
*(pSourceData + j * image_pitch + i * 3 + 1) = 0;//G
*(pSourceData + j * image_pitch + i * 3 + 2) = 0;//B
}
if (image_bpp == 32){
b = *(pSourceData + j * image_pitch + i * 4);
g = *(pSourceData + j * image_pitch + i * 4 + 1);
r = *(pSourceData + j * image_pitch + i * 4 + 2);
alpha = *(pSourceData + j * image_pitch + i * 4 + 3);
//进行RGB设置
*(pSourceData + j * image_pitch + i * 4) = 0;//B
*(pSourceData + j * image_pitch + i * 4 + 1) = 0;//G
*(pSourceData + j * image_pitch + i * 4 + 2) = 175;//R
*(pSourceData + j * image_pitch + i * 4 + 3) = 0;
}
}
}
这篇关于CImage 设置任意像素的RGB值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!