如何在64位机器中保存8位bmp图像?在32位机器上运行良好

时间:2012-05-07 04:30:50

标签: c++

以下提到的代码;在32位机器上运行良好,但它不能在64位机器上运行..

任何想法/建议 - 以及如何解决这个问题? 你觉得怎么样 - 在64 MACHINE中保存图像8位BMP

void BMPFile::SaveBMP(char* fileName,BYTE * buf,UINT width,UINT height)
{
    short res1=0;
    short res2=0;
    long pixoff=54;
    long compression=0;
    long cmpsize=0;
    long colors=0;
    long impcol=0;
    char m1='B';
    char m2='M';

    DWORD widthDW = WIDTHBYTES(width *24);

    long bmfsize=sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) +
                            widthDW * height;   
    long byteswritten=0;

    BITMAPINFOHEADER header;
    header.biSize=40;                       // header size
    header.biWidth=width;
    header.biHeight=height;
    header.biPlanes=1;
    header.biBitCount=24;                   // RGB encoded, 24 bit
    header.biCompression=BI_RGB;            // no compression
    header.biSizeImage=0;
    header.biXPelsPerMeter=0;
    header.biYPelsPerMeter=0;
    header.biClrUsed=0;
    header.biClrImportant=0;

    FILE *fp;   
    fp=fopen(fileName,"wb");
    if (fp==NULL)
    {
        return;
    }

    // should probably check for write errors here...

    fwrite((BYTE  *)&(m1),1,1,fp); byteswritten+=1;
    fwrite((BYTE  *)&(m2),1,1,fp); byteswritten+=1;
    fwrite((long  *)&(bmfsize),4,1,fp); byteswritten+=4;
    fwrite((int  *)&(res1),2,1,fp); byteswritten+=2;
    fwrite((int  *)&(res2),2,1,fp); byteswritten+=2;
    fwrite((long  *)&(pixoff),4,1,fp); byteswritten+=4;

    fwrite((BITMAPINFOHEADER *)&header,sizeof(BITMAPINFOHEADER),1,fp);
    byteswritten+=sizeof(BITMAPINFOHEADER);

    long row=0;
    long rowidx;
    long row_size;
    row_size=header.biWidth*3;
    long rc;
    for (row=0;row<header.biHeight;row++) 
    {
        rowidx=(long unsigned)row*row_size;                           

        // write a row
        rc=fwrite((void  *)(buf+rowidx),row_size,1,fp);
        if (rc!=1) 
        {
            break;
        }
        byteswritten+=row_size; 

        // pad to DWORD
        for (DWORD count=row_size;count<widthDW;count++) {
            char dummy=0;
            fwrite(&dummy,1,1,fp);
            byteswritten++;                           
        }
    }             
    fclose(fp);
}

1 个答案:

答案 0 :(得分:1)

编辑: 我再次看了windows标题,我错过了#pragma pack。因此,对齐不是问题。

通常,如果需要将固定大小的值写入磁盘,请使用显式大小的数据类型,因为int / long等的大小可能因编译器和体系结构而异。在ANSI平台上,你包含“stdint.h”,在visual c上你可以输入这些:

typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;