C++实现BMP图像旋转90度

先定义两个结构,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算法优化处理。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值