【发布时间】:2020-07-28 17:46:14
【问题描述】:
我尝试读取位图文件。这是我的程序:
#include<iostream>
#include<fstream>
#include <string>
#include<windows.h>
using namespace std;
#pragma pack(1)
struct header
{
char header[2];
int32_t filesize;
int16_t reser;
int16_t reser1;
int32_t dataoffset;
};
struct infoheader
{
int32_t headersize;
int32_t width;
int32_t height;
int16_t plans;
int16_t bpp;
int32_t compression;
int32_t datasize;
int32_t re;
int32_t ve;
int32_t color;
int32_t importantcolor;
};
struct PIxel
{
unsigned char G;
unsigned char B;
unsigned char R;
};
int main()
{
header h;
infoheader info;
PIxel *p;
ifstream file("bmp2.bmp", ios::binary);
if (file.is_open())
{
cout << "true" << endl;
file.read((char*)&h, sizeof(h));
file.read((char*)&info, sizeof(info));
cout << info.width << " " << info.height << " " << h.filesize << " " << info.bpp << endl;
int pa = info.width % 4;
int size = info.width * info.height * (info.bpp / 3) + pa * info.height;
char* arr = new char[size];
file.read(arr, size);
char* temp = arr;
int sizep = info.height * info.width;
p = new PIxel[sizep];
for (int i = 0; i < info.height; i++)
{
for (int j = 0; j < info.width; j++)
{
p[i * info.height + j].B = *(temp++);
p[i * info.height + j].G = *(temp++);
p[i * info.height + j].R = *(temp++);
//p = p + 3;
}
p += pa;
}
HWND consoleWindow = GetConsoleWindow();
HDC hdc = GetDC(consoleWindow);
for (int i = 0; i < info.height; i++)
{
for (int j = 0; j < info.width; j++)
{
PIxel m = p[i * info.height + j];
SetPixel(hdc, i, j, RGB(m.R, m.G, m.B));
}
}
ReleaseDC(consoleWindow, hdc);
}
}
它可以工作,但我控制台上的图像不正确...
你能帮我解决它吗?
【问题讨论】:
-
看起来每行填充有问题。尽管您的代码似乎正在使用填充。
-
我认为
p += pa;是错误的。您想通过填充而不是p推进temp。p是目的地。源是有填充的。 -
在控制台窗口上绘图也不是一个好主意。
-
为什么不使用
BITMAPFILEHEADER、BITMAPINFOHEADER和RGBTRIPLE。你硬编码24bpp bmp。您的代码不适用于另一个 bpp。为什么不使用CreateDIBSection和BitBlt -
Windows Imaging Component 带有一个 bitmap decoder,这样我们就不必处理这些内部问题,也不会弄错。
标签: c++ file winapi struct bitmap