从像素数组加载颜色值

时间:2012-02-20 22:55:21

标签: c++ bmp

我读了这篇关于位图的教程http://tipsandtricks.runicsoft.com/Cpp/BitmapTutorial.html,它确实有帮助。我需要从像素数组的元素中读取颜色整数值。怎么做? 好的是将数据放入rgb数组的代码

BYTE* ConvertBMPToRGBBuffer ( BYTE* Buffer, int width, int height )
{

if ( ( NULL == Buffer ) || ( width == 0 ) || ( height == 0 ) )
    return NULL;

// find the number of padding bytes

int padding = 0;
int scanlinebytes = width * 3;
while ( ( scanlinebytes + padding ) % 4 != 0 )     // DWORD = 4 bytes
    padding++;
// get the padded scanline width
int psw = scanlinebytes + padding;

// create new buffer
BYTE* newbuf = new BYTE[width*height*3];

// now we loop trough all bytes of the original buffer, 
// swap the R and B bytes and the scanlines
long bufpos = 0;   
long newpos = 0;
for ( int y = 0; y < height; y++ )
    for ( int x = 0; x < 3 * width; x+=3 )
    {
        newpos = y * 3 * width + x;     
        bufpos = ( height - y - 1 ) * psw + x;

        newbuf[newpos] = Buffer[bufpos + 2];       
        newbuf[newpos + 1] = Buffer[bufpos+1]; 
        newbuf[newpos + 2] = Buffer[bufpos];     
    }

return newbuf;
    }

1 个答案:

答案 0 :(得分:2)

您的图像看起来像RGB交错格式。要获得(x,y)处的像素,只需在该位置索引数组即可。如果缓冲区指向结构类型,那将是最简单的。类似的东西:

typedef struct RGBPixel {
    BYTE red;
    BYTE green;
    BYTE blue;
} RGBPixel;

然后你可以这样做:

RGBPixel* pixels = (RGBPixel*)newbuf;

要获得(x,y)的像素,你可以这样做:

RGBPixel aPixel = pixels [ y * width + x ];