1. 程式人生 > >C語言實現BMP影象旋轉

C語言實現BMP影象旋轉

 實現影象旋轉,首先要對影象的儲存,影象的讀寫比較清楚,在此基礎上進行線性變換。以下程式碼為逆時針旋轉90度,後續會給出旋轉任意角度的程式碼:

核心還是掌握旋轉時的前後變換。變換的過程可以歸結為:首先將影象座標變換為數學座標,然後在數學座標上進行變換,然後在進行逆變換,得到在影象座標上的變換。同時需要求出各個變換的逆變換。


#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
	FILE *fp = fopen("./01.bmp", "rb");
	if (fp == 0){
		printf("檔案開啟失敗\n");
		return 0;
	}

	BITMAPFILEHEADER fileHead;
	BITMAPINFOHEADER infoHead;
	fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
	fread(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);

	int width = infoHead.biWidth;
	int height = infoHead.biHeight;
	int biCount = infoHead.biBitCount;
	int lineByte = (width*biCount / 8 + 3) / 4 * 4;

	RGBQUAD *pColorTable;

	pColorTable = new RGBQUAD[256];
	fread(pColorTable, sizeof(RGBQUAD), 256, fp);

	unsigned char *pBmpBuf;
	pBmpBuf = new unsigned char[lineByte*height];
	fread(pBmpBuf, lineByte*height, 1, fp);
	fclose(fp);
	
	// 右旋轉90
	unsigned char *pBmpBuf3;
	int lineByte3 = (height*biCount / 8 + 3) / 4 * 4;

	pBmpBuf3 = new unsigned char[lineByte3*width];
	for (int i = 0; i < width; ++i){
		for (int j = 0; j < height; ++j){
			unsigned char *p;
			p = (unsigned char *)(pBmpBuf3 + lineByte3*i + j);
			(*p) = 255;
		}
	}
	for (int i = 0; i < width; ++i){
		for (int j = 0; j < height; ++j){
			unsigned char *p,*p3;
			p = (unsigned char *)(pBmpBuf + lineByte*j + i);  // 原影象
			p3 = (unsigned char *)(pBmpBuf3 + lineByte3*i + height-j-1);// 新影象
			(*p3) = (*p);
		}
	}

	FILE *fpo = fopen("./rotate90N.bmp", "wb");
	if (fpo == 0)
		return 0;
	
	fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fpo);
    
	BITMAPINFOHEADER infoHead3;
	infoHead3.biBitCount = biCount;
	infoHead3.biClrImportant = 0;
	infoHead3.biClrUsed = 0;
	infoHead3.biCompression = 0;
	infoHead3.biHeight = width;
	infoHead3.biPlanes = 1;
	infoHead3.biSize = 40;
	infoHead3.biSizeImage = lineByte3*width;
	infoHead3.biWidth = height;
	infoHead3.biXPelsPerMeter = 0;
	infoHead3.biYPelsPerMeter = 0;

	fwrite(&infoHead3, sizeof(BITMAPINFOHEADER), 1, fpo);
	fwrite(pColorTable, sizeof(RGBQUAD), 256, fpo);
	fwrite(pBmpBuf3, lineByte3*width, 1, fpo);
	fclose(fpo);

	system("pause");
	return 1;
}

實驗結果:

       原圖                                         逆時針旋轉90度