【发布时间】:2014-08-17 15:50:34
【问题描述】:
我正在尝试创建自己的类来操作 BMP 图像..
我从这个简单的代码开始:
本维基百科link.中给出的一切都已完成
我有两个问题:
-
当我尝试打开图片时出现错误
Premature end of file detected 我创建的实际文件超出了应有的文件大小两个字节。
代码如下:
#include <fstream>
#include <iostream>
using namespace std;
struct BMP_Header
{
public :
char id[2];
unsigned int total_image_size;
short int app_data1,app_data2;
unsigned int offset;
};
struct DIB_Header
{
public :
unsigned int dib_header_size;
int image_width;
int image_height;
short int no_colour_planes;
short int colour_depth;
unsigned int compression_method;
unsigned int raw_image_size;
unsigned int horizontal_resolution;
unsigned int vertical_resolution;
unsigned int num_colours_palette;
unsigned int imp_colours_used;
};
int main ()
{
int index=0;
BMP_Header bmp_header;
DIB_Header dib_header;
char pixel_array[16];
bmp_header.total_image_size=70;
bmp_header.offset=54;
bmp_header.id[0]='B';
bmp_header.id[1]='M';
bmp_header.app_data1=0;
bmp_header.app_data2=0;
dib_header.dib_header_size=40;
dib_header.image_width=2;
dib_header.image_height=2;
dib_header.colour_depth=24;
dib_header.raw_image_size=16;
dib_header.horizontal_resolution=2835;
dib_header.vertical_resolution=2835;
dib_header.no_colour_planes=1;
dib_header.compression_method=0;
dib_header.num_colours_palette=0;
dib_header.imp_colours_used=0;
pixel_array[index++]=0;
pixel_array[index++]=0;
pixel_array[index++]=255;
pixel_array[index++]=255;
pixel_array[index++]=255;
pixel_array[index++]=255;
pixel_array[index++]=0;
pixel_array[index++]=0;
pixel_array[index++]=255;
pixel_array[index++]=0;
pixel_array[index++]=0;
pixel_array[index++]=0;
pixel_array[index++]=255;
pixel_array[index++]=0;
pixel_array[index++]=0;
pixel_array[index++]=0;
// Image Made
fstream file;
file.open ("abc.bmp",ios::out | ios::binary);
file.write ((char*)&bmp_header,sizeof (bmp_header));
file.write ((char*)&dib_header,sizeof (dib_header));
file.write ((char*)pixel_array,sizeof (pixel_array));
file.close ();
return 0;
}
【问题讨论】:
-
这段代码只将一个条目放入
pixel_array数组中。您可能希望在此处使用循环,以便覆盖数组中的每个index。此外,我强烈建议在这些原始数组上使用 c++ 标准库容器,例如std::vector或std::array。 -
我已经初始化了像素数组的所有元素......请看看......
-
考虑使用
struct来明确BMP_Header和DIB_Header应该是POD。还可以考虑将成员初始化器直接放在成员声明上,这样您就可以删除自定义构造函数...接下来,您确定需要将这些强制转换为char*? -
好的...会尝试这样做..btw 什么是 POD....?
-
除此之外,您应该使用固定宽度类型,否则在另一个平台/编译器上,您可能会因为不同的大小类型而弄乱内存布局。