bmp图像顺时针旋转90度c++
时间: 2023-10-01 11:05:56 浏览: 120
BMP_Reverse_90_degree.rar_bmp图像旋转_bmp旋转90°_图像旋转90度
bmp图像顺时针旋转90度的大致思路是将原图像中每个像素的位置进行变换,然后重新生成新的图像。以下是一个基本的C++代码示例:
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
#pragma pack(2) //按2字节对齐
typedef struct tagBITMAPFILEHEADER {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;
#pragma pack()
typedef struct tagBITMAPINFOHEADER {
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;
} BITMAPINFOHEADER;
void rotate90(char* inputFileName, char* outputFileName) {
ifstream input(inputFileName, ios::in | ios::binary);
if (!input) {
cerr << "Error: Can not open input file." << endl;
exit(1);
}
ofstream output(outputFileName, ios::out | ios::binary);
if (!output) {
cerr << "Error: Can not open output file." << endl;
exit(1);
}
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
input.read((char*)&fileHeader, sizeof(BITMAPFILEHEADER));
if (fileHeader.bfType != 0x4d42) {
cerr << "Error: Invalid BMP file format." << endl;
exit(1);
}
input.read((char*)&infoHeader, sizeof(BITMAPINFOHEADER));
if (infoHeader.biBitCount != 24) {
cerr << "Error: Only support 24-bit BMP image." << endl;
exit(1);
}
// 计算新图像的宽度和高度
int newWidth = infoHeader.biHeight;
int newHeight = infoHeader.biWidth;
// 计算新图像每行的字节数和每个像素的字节数
int newLineByte = (newWidth * 3 + 3) / 4 * 4;
int pixelByte = 3;
// 计算新图像的文件大小和图像数据大小
int newImageSize = newLineByte * newHeight;
int newFileSize = fileHeader.bfOffBits + newImageSize;
// 生成新的文件头和信息头
BITMAPFILEHEADER newFileHeader = fileHeader;
newFileHeader.bfSize = newFileSize;
BITMAPINFOHEADER newInfoHeader = infoHeader;
newInfoHeader.biWidth = newWidth;
newInfoHeader.biHeight = newHeight;
newInfoHeader.biSizeImage = newImageSize;
output.write((char*)&newFileHeader, sizeof(BITMAPFILEHEADER));
output.write((char*)&newInfoHeader, sizeof(BITMAPINFOHEADER));
// 读取原图像中每一行的数据,进行旋转后写入新图像中
char* lineData = new char[newLineByte];
memset(lineData, 0, newLineByte);
for (int i = 0; i < infoHeader.biHeight; i++) {
input.read(lineData, infoHeader.biWidth * pixelByte);
for (int j = 0; j < infoHeader.biWidth; j++) {
int x = i;
int y = j;
// 计算旋转后的位置
int newX = y;
int newY = newWidth - 1 - x;
// 将像素数据写入新图像中
output.seekp(newFileHeader.bfOffBits + newY * newLineByte + newX * pixelByte);
output.write(lineData + j * pixelByte, pixelByte);
}
}
delete[] lineData;
input.close();
output.close();
}
int main() {
rotate90("input.bmp", "output.bmp");
return 0;
}
```
这个例子中,我们首先读取了原图像的文件头和信息头,然后计算了新图像的宽度和高度,以及每行的字节数和像素的字节数。接着,我们生成了新的文件头和信息头,并将它们写入输出文件中。最后,我们遍历原图像中的每一行像素数据,进行旋转后写入新图像中。
阅读全文