尝试创建多种尺寸的位图文件

时间:2019-04-04 07:32:55

标签: c++ bitmap

我当前的程序可以创建128个像素乘以128个像素,256个像素乘以256个像素,1024个像素乘以1024个像素的位图文件,依此类推。我正在尝试获取当前代码以创建大小为400像素乘400像素的位图文件,但是在尝试进行此更改时收到错误消息,指出它不是有效的位图文件或不被支持。

对于3个成功试验,我要做的就是更改下面显示的IMAGE_SIZE值。当我将IMAGE_SIZE更改为400以创建400 x 400尺寸时,出现了错误。

我尝试更改的部分

#define IMAGE_SIZE 256
#include <iostream>
#include <fstream>
#include "windows.h"
using namespace std;
// The following defines the size of the square image in pixels.
#define IMAGE_SIZE 256
int main(int argc, char* argv[])
{

    BITMAPFILEHEADER bmfh;

    BITMAPINFOHEADER bmih;

    char colorTable[8] = { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff };

    // The following defines the array which holds the image.  The row length 
    // (number of columns) is the height divided by 8, since there are 8 bits
    // in a byte.
    char bits[IMAGE_SIZE][IMAGE_SIZE / 8];

    // Define and open the output file. 
    ofstream bmpOut("foo.bmp", ios::out + ios::binary);
    if (!bmpOut) {
        cout << "...could not open file, ending.";
        return -1;
    }
    // Initialize the bit map file header with static values.
    bmfh.bfType = 0x4d42;
    bmfh.bfReserved1 = 0;
    bmfh.bfReserved2 = 0;
    bmfh.bfOffBits = sizeof(bmfh) + sizeof(bmih) + sizeof(colorTable);
    bmfh.bfSize = bmfh.bfOffBits + sizeof(bits);

    // Initialize the bit map information header with static values.
    bmih.biSize = 40;
    bmih.biWidth = IMAGE_SIZE;
    bmih.biHeight = IMAGE_SIZE;
    bmih.biPlanes = 1;
    bmih.biBitCount = 1;
    bmih.biCompression = 0;
    bmih.biSizeImage = 0;
    bmih.biXPelsPerMeter = 2835;  // magic number, see Wikipedia entry
    bmih.biYPelsPerMeter = 2835;
    bmih.biClrUsed = 0;
    bmih.biClrImportant = 0;

    // Build monochrome array of bits in image
    for (int i = 0; i < IMAGE_SIZE; i++) {
        for (int j = 0; j < IMAGE_SIZE / 8; j++) {
            bits[i][j] = 0x0f;
        }
    }

    // Write out the bit map.  
    char* workPtr;
    workPtr = (char*)&bmfh;
    bmpOut.write(workPtr, 14);
    workPtr = (char*)&bmih;
    bmpOut.write(workPtr, 40);
    workPtr = &colorTable[0];
    bmpOut.write(workPtr, 8);
    workPtr = &bits[0][0];
    bmpOut.write(workPtr, IMAGE_SIZE*IMAGE_SIZE / 8);
    bmpOut.close();

    // showing result
    system("mspaint foo.bmp");

    // Done.
    return 0;
}

0 个答案:

没有答案