1. 程式人生 > >C++——bmp影象裁剪

C++——bmp影象裁剪

在之前的部落格中,我們已經實現了bmp影象的讀取與儲存,本文在之前的基礎上對對人影象的資料區進行處理,達到擷取影象部分割槽域的目的,以便以後的影象處理操作,程式碼如下:

#include <string.h>       
#include <malloc.h>  
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<time.h>//時間相關標頭檔案,可用其中函式計算影象處理速度  
#include"readbmp.h"
#include"savebmp.h"

void image_cut()
{
	unsigned char *imagedata = NULL; //動態分配儲存原圖片的畫素資訊的二維陣列
	unsigned char *imagedataCut = NULL;//動態分配儲存裁剪後的圖片的畫素資訊的二維陣列
	char readPath[] = "D:\\C++_file\\image_deal_C++\\IMAGE_JIEQU\\lunpan.bmp";
	readBmp(readPath);
	imagedata = pBmpBuf;
	//===========================================圖片裁剪處理====================================================//
	int leftdownx, leftdowny, rightupx, rightupy;/////使用者輸入數值
	int Rleftdownx, Rleftdowny, Rrightupx, Rrightupy;/////轉換成實際可以使用數值
	cout << "請輸入要裁剪的矩形區域的左下角和右上角的座標(連續四個整數值,如50 50 300 300):" << endl;
	cin >> leftdownx;
	cin >> leftdowny;
	cin >> rightupx;
	cin >> rightupy;
	//------------------------將使用者輸入的矩形框限定在原影象中--------------------------------//
	if (leftdownx < 0 && leftdowny < 0)
		{
		Rleftdownx = 0;
		Rleftdowny = 0;
		}
	else if (leftdownx <= 0 && leftdowny >= 0)
		{
			Rleftdownx = 0;
			Rleftdowny = leftdowny;
		}
	else if (leftdownx >= 0 && leftdowny <= 0)
		{
			Rleftdownx = leftdownx;
			Rleftdowny = 0;
		}
	else if(leftdownx > 0 && leftdowny > 0)
		{
			Rleftdownx = leftdownx;
			Rleftdowny = leftdowny;
		}

	if (rightupx >= bmpWidth)
		{
			Rrightupx = bmpWidth;
		}
	else
		{
			Rrightupx = rightupx;
		}
	if (rightupy >= bmpHeight)
		{
			Rrightupy = bmpHeight;
		}
	else
		{
			Rrightupy = rightupy;
		}


	int CutWidth, CutHeight;
	CutWidth = Rrightupx - Rleftdownx;
	CutHeight = Rrightupy - Rleftdowny;////矩形框實際高度

	int lineByte2 = (CutWidth * biBitCount / 8 + 3) / 4 * 4;//灰度影象有顏色表,且顏色表表項為256
	imagedataCut = new unsigned char[lineByte2 * CutHeight];
	//---------------------------原始影象資料陣列指標移動到矩形框的左下角。-------------------------------------------//
	
	imagedata = imagedata + (Rleftdowny)*bmpWidth*3 ;

	//----------------------------裁剪區域資料提取-------------------------------------------//
	for (int i = 0; i < CutHeight; i++)
	{
		for (int j = 0; j < CutWidth; j++)
			for (int k = 0; k < 3; k++)
				*(imagedataCut + i *lineByte2 + j * 3 + k) = *(imagedata + i * bmpWidth * 3 + j * 3 + k + Rleftdownx*3);////此式子一定要注意寫法。主要是注意二維陣列指標的用法。

	}

	char writePath[] = "D:\\C++_file\\image_deal_C++\\IMAGE_JIEQU\\1.bmp";
	saveBmp(writePath, imagedataCut, CutWidth, CutHeight, biBitCount, pColorTable);
	printf("裁剪變換完成,請檢視bmp檔案。\n\n");

	//釋放記憶體
	//delete[] imagedata;///不能釋放imagedata,裡面還有資料。
	delete[] imagedataCut;
}
int main()
{
	...
	
}
讀寫程式仍然用的是之前部落格中所給出的函式。根據此程式即可完成影象擷取的操作,經過試驗,針對各種輸入情況,均可得到正確擷取結果。