先定义两个结构,BMP文件头结构跟BMP信息头结构
// BMP文件头结构
#pragma pack(push, 1)
struct BITMAPFILEHEADER {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
};
// BMP信息头结构
struct BITMAPINFOHEADER {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
};
#pragma pack(pop)
读取文件:
std::string strFilePath = "";
std::ifstream file(strFilePath, std::ios::binary);
if (!file){
//open failed
}
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
//read header
file.read(reinterpret_cast<char*>(&fileHeader), sizeof(fileHeader));
//read info
file.read(reinterpret_cast<char*>(&infoHeader), sizeof(infoHeader));
if (fileHeader.bfType!= 0x4D42){//判断是否为bmp
//TODO:
}
int width = infoHeader.biWidth;
int height = infoHeader.biHeight;
int bitCount = infoHeader.biBitCount;
// 计算每行的字节数,确保是4的倍数
int padding = (4 - (width * (bitCount / 8) % 4)) % 4;
// 读取像素数据
std::vector<unsigned char> pixelData;
pixelData.resize(height * (width * (bitCount / 8)+padding));
file.read(reinterpret_cast<char*>(pixelData.data()), pixelData.size());
file.close();
拿到像素后之后做旋转操作:此处按32位深处理
std::shared_ptr<unsigned char> pixels32(new unsigned char[((width * 4 + paddingIn) * height)]);
memcpy(pixels32.get(), pData.get(), ((width * 4 + paddingIn) * height));
//对图像进行旋转90°操作
std::vector<unsigned char> rotatedPixels(height * width * 4);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int newX = height - 1 - y;
int newY = width - 1 - x;
int index = (newY * height + newX) * 4;
int originalIndex = (y * width + x) * 4;
rotatedPixels[index] = pixels32.get()[originalIndex];
}
}
另外如果嫌弃处理速度慢也可使用SSE算法优化处理。
301

被折叠的 条评论
为什么被折叠?



