c++:将 24bpp 转换为 8bpp 或 1bpp 图像

c++: Convert 24bpp to 8 bpp or 1bpp image

我必须根据颜色 table 将 24bpp 图像转换为 1bpp 图像或 8bpp 图像。在任何一种情况下,调用者都期望 unsigned char*(这将被进一步处理,或者现在可能通过将 BITMAPINFOHEADER.biBitCount 发送到它的正确值 8 或 1 来调试输出)。

我有将颜色索引提取到调色板中的代码(colorIndexArray 来自颜色转换或抖动算法)...我可以获得 8bpp 位图的信息...

但我的问题是,我不知道如何将此信息放入 1bpp 位图中

typedef struct {
    unsigned int size;
    unsigned char* pixels;
} ColorIndexArray;

unsigned char* convertImage(const ColorIndexArray& colorIndexArray, unsigned int paletteSize)
{
    unsigned char* outputImage;
    if (paleteSize > 2)
    {
        outputImage = (unsigned char*)LocalAlloc(LPTR, colorIndexArray.size);
        for (int i=0; i<colorIndexArray.size; i++)
            *(outputImage+i) = colorIndexArray.pixels[i];  
        // this works great              
    }
    else  // monochrome, caller has palette colors likely b/w (or purple/magenta or anything), must be 1bpp
    {
        outputImage = (unsigned char*)LocalAlloc(LPTR, colorIndexArray.size / 8);
        // how can i place the unsigned char* info (which is already 
        // determined based on desired algorithm, representing index in 
        // color table) into the output image inside a single bit ?
        // (obviously its value for a monochrome image would be 0 or 1 but    
        // it is saved as unsigned char* at the algorithm output) 
        // And how do I advance the pointer ?
        // Will it be type safe ? Aligned to byte ? or do I have to fill 
        // with something at the end to make multiple of 8 bits ?
    }

    return outputImage;
}

在评论建议后尝试此操作:

#include <GdiPlus.h>
....
else {
    Gdiplus::Bitmap monoBitmap(w, h, PixelFormat1bppIndexed);
    Gdiplus::BitmapData monoBitmapData;
    Gdiplus::Rect rect(0, 0, w, h);
    monoBitmap.LockBits(&rect, Gdiplus::ImageLockModeWrite, PixelFormat1bppIndexed, &monoBitmapData);
    outputImage = (unsigned char*)monoBitmapData.Scan0;

    for (unsigned int y = 0; y < h; y++)
    {
        for (unsigned int x = 0; x < w; x++)
        {
            if (colorIndexArray.pixels[x + y * w])
                outputImage[y*monoBitmapData.Stride + x / 8] |= (unsigned char)(0x80 >> (x % 8));
        }           
    }
    monoBitmap.UnlockBits(&monoBitmapData); 
}
return outputImage;

(还需要为outputImage分配内存)

根据Hans Passant推荐的例子(也谢谢你指出stride的重要性),我写了这个小转换

unsigned long stride = (((w + 31) & ~31) >> 3); 

outputImage = (unsigned char*)LocalAlloc(LPTR, stride * h);

for (unsigned int y = 0; y < h; y++)
{           
    unsigned char* b = (unsigned char*)LocalAlloc(LPTR, stride);
    for (unsigned int x = 0; x < w; x++)
        if (colorIndexArray.pixels[x + y * w])
            b[x / 8] |= (unsigned char)(0x80 >> (x % 8));               
    CopyMemory(outputImage + stride * y, b, stride);
}