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

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

本文关键字:bpp 1bpp 图像 24bpp 转换 c++      更新时间:2023-10-16

我必须根据颜色表将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;

(还需要为输出图像分配内存)

基于Hans Passant建议的例子(也感谢您指出步幅的重要性),我写了这个小转换

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);
}