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

时间:2015-01-16 19:01:29

标签: c++ image bitmap byte monochrome

我必须根据颜色表将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分配内存)

1 个答案:

答案 0 :(得分:1)

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