这个程序是我在别人的基础上修改的,还可以实现输出剪裁前和剪裁后的数据进入txt中,链接找不到了
#include<stdio.h>
#include<windows.h>
#define MYCUT_HEIGHT 100 //截取高度
#define MYCUT_WIDTH 100 //截取宽度
#define BEGIN_X 80 //截取位图开始位置X坐标
#define BEGIN_Y 80 //截取位图开始位置Y坐标
int main()
{
int bmpHeight;
int bmpWidth;
unsigned char* pBmpBuf;
unsigned char* pBmpBuf2;
RGBQUAD* pColorTable;
int biBitCount;
//读取bmp文件
FILE* fp = fopen("C:\\Users\\27681\\Desktop\\test\\cut\\lena.BMP", "rb");
if (fp == 0)
return 0;
BITMAPFILEHEADER fileHead;
fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
BITMAPINFOHEADER head;
fread(&head, 40, 1, fp);
bmpHeight = head.biHeight;
bmpWidth = head.biWidth;
biBitCount = head.biBitCount;
pColorTable = new RGBQUAD[256];
fread(pColorTable, sizeof(RGBQUAD), 256, fp);
int LineByte = (bmpWidth * biBitCount / 8 + 3) / 4 * 4;//保证每一行字节数都为4的整数倍
pBmpBuf = new unsigned char[LineByte * bmpHeight];
fread(pBmpBuf, LineByte * bmpHeight, 1, fp);
/*以下是获得裁剪前原图的数据并打印保存*/
printf("以下是获得裁剪前原图的数据\n");
FILE* fs = fopen("C:\\Users\\27681\\Desktop\\test\\cut\\获得裁剪前的数据.txt", "w");
for (int i = 0; i < bmpHeight; i++)
{
for (int j = 0; j < bmpWidth; j++)
{
// 获取循环到像元的像素值
unsigned char pixel = pBmpBuf[j + i * bmpWidth];
// 这里打印一下读出的像元
printf("%d ", pixel);
// 保存到文件中
fprintf(fs, "%d ", pixel);
}
// 打印一行后换行
printf("\n");
// 完成一行像素的保存后换行继续进行保存
fprintf(fs, "\n");
}
fclose(fs);
fclose(fp);
FILE* fop = fopen("C:\\Users\\27681\\Desktop\\test\\cut\\lena1.BMP", "wb");
head.biHeight = MYCUT_HEIGHT;//为截取文件重写位图高度
head.biWidth = MYCUT_WIDTH;//为截取文件重写位图宽度
int LineByte2 = (head.biWidth * biBitCount / 8 + 3) / 4 * 4;
pBmpBuf2 = new unsigned char[LineByte * head.biHeight];
head.biSizeImage = LineByte2 * head.biHeight;
fileHead.bfSize = head.biSizeImage + fileHead.bfOffBits;
fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fop);
fwrite(&head, sizeof(BITMAPINFOHEADER), 1, fop);
fwrite(pColorTable, sizeof(RGBQUAD), 256, fop);
for (int i = 0; i < MYCUT_HEIGHT; ++i) {
for (int j = 0; j < MYCUT_WIDTH; ++j)
{
pBmpBuf2[i * MYCUT_WIDTH + j] = pBmpBuf[(BEGIN_Y + i) * bmpWidth + BEGIN_X + j];
}
}
/*以下是获得裁剪后的数据并打印保存*/
printf("以下是获得裁剪后的数据\n");
FILE* lata = fopen("C:\\Users\\27681\\Desktop\\test\\cut\\获得裁剪后的数据.txt", "w");
for (int i = 0; i < MYCUT_HEIGHT; i++)
{
for (int j = 0; j < MYCUT_WIDTH; j++)
{
// 获取循环到像元的像素值
unsigned char pixel = pBmpBuf2[j + i * MYCUT_WIDTH];
// 这里打印一下读出的像元
printf("%d ", pixel);
// 保存到文件中
fprintf(lata, "%d ", pixel);
}
// 打印一行后换行
printf("\n");
// 完成一行像素的保存后换行继续进行保存
fprintf(lata, "\n");
}
fclose(lata);
fwrite(pBmpBuf2, LineByte2 * head.biHeight, 1, fop);
fclose(fop);
system("pause");
return 0;
}