24位bmp剪切并转存为单色bmp

 
折磨我好久啊。。。可惜弄好了又用不上了。。。

知识关键:
Bmp文件有个重要特性,那就是对于数据区域而言,每行的数据它必须凑满4字节,如果没有满,则用冗余的数据来补齐。

程序关键:
bi.biSizeImage = (bi.biWidth*bi.biBitCount+31)/32*4*bi.biHeight; //生成的新图像的文件大小

/* 实现原图像坐标的转换读取 */
pitch = SrcWidth%4;
int realPitch = i*pitch;
BYTE b = pDIBData[(i*SrcWidth+j)*3+realPitch];
BYTE g = pDIBData[(i*SrcWidth+j)*3+1+realPitch];
BYTE r = pDIBData[(i*SrcWidth+j)*3+2+realPitch];

输入input.bmp 输出output.bmp
主要参考:百度百科_BMP http://baike.baidu.com/view/7671.htm (BMP文件存储格式)
BMP图象解析 http://www.vckbase.com/document/viewdoc/?id=1786 (坐标位置转换)
__________________________________________________________________________________
void CutPhoto(long StartLeft, long StartTop, long TargetWidth, long TargetHeight)
{
    char FileName[32];
    sprintf(FileName, "input.bmp");

    BYTE* pDIBData;
    BITMAPFILEHEADER bf;
    BITMAPINFOHEADER bi;
    RGBQUAD rgb[2]={{0,0,0,0},{255,255,255,0}};
   
    CFile fileR(FileName, CFile::modeRead);
    fileR.Read(&bf, sizeof(BITMAPFILEHEADER));
    fileR.Read(&bi, sizeof(BITMAPINFOHEADER));
    long SrcWidth=bi.biWidth;
    long SrcHeight=bi.biHeight;
    int nSize = bf.bfSize - bi.biSize;
    pDIBData = new BYTE[nSize];
    fileR.Read(pDIBData, nSize);
    fileR.Close();

    StartTop = SrcHeight - TargetHeight - StartTop;
    bi.biWidth = TargetWidth;
    bi.biHeight = TargetHeight;
    bi.biBitCount = 1;
    bi.biXPelsPerMeter = 0;
    bi.biYPelsPerMeter = 0;
    bi.biSizeImage = (bi.biWidth*bi.biBitCount+31)/32*4*bi.biHeight;

    sprintf(FileName, "output.bmp");
    CFile file(FileName, CFile::modeWrite|CFile::modeCreate);
    bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*2;
    bf.bfSize = bf.bfOffBits + bi.biSizeImage;
    file.Write(&bf, sizeof(BITMAPFILEHEADER));
    file.Write(&bi, sizeof(BITMAPINFOHEADER));
    file.Write(rgb, 2*sizeof(RGBQUAD));

    BYTE writein = 0;
    int pitch = SrcWidth%4;
    int k, pitchcount;
    for(int i=StartTop;i<StartTop+TargetHeight;i++)
    {
        pitchcount = 0;
        k=0;
        int realPitch = i*pitch;
        for(int j=StartLeft;j<StartLeft+TargetWidth;j++)
        {
            BYTE b = pDIBData[(i*SrcWidth+j)*3+realPitch];
            BYTE g = pDIBData[(i*SrcWidth+j)*3+1+realPitch];
            BYTE r = pDIBData[(i*SrcWidth+j)*3+2+realPitch];
            writein<<=1;
            if ((r+g+b)/3>127)
                writein|=1;
            if (++k==8)
            {
                pitchcount++;
                file.Write(&writein, 1);
                writein = 0;
                k=0;
            }
        }
        if (k != 0)
        {
            writein<<=(8-k);
            file.Write(&writein, 1);
            pitchcount++;
        }
        if (pitchcount%4 != 0)
        {
            writein = 0;
            for (j=0; j<4-pitchcount%4; j++)
                file.Write(&writein, 1);
        }
    }
    file.Close();
    delete pDIBData;
    pDIBData = NULL;
}

你可能感兴趣的:(百度,File,null,BI,delete,byte)