能读取影像的影像旋转25度的C语言代码,每一行添加注释
时间: 2023-06-13 15:08:21 浏览: 67
以下是能读取影像的影像旋转25度的C语言代码,每一行都添加了注释说明:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int main()
{
// 打开原始影像文件
FILE *fp_src = fopen("source_image.bmp", "rb");
if (fp_src == NULL) {
printf("Failed to open source image file!");
return 1;
}
// 读取 BMP 文件头
unsigned char bmp_header[54];
fread(bmp_header, sizeof(unsigned char), 54, fp_src);
// 获取位图信息头中的宽度和高度信息
int width = *(int*)&bmp_header[18];
int height = *(int*)&bmp_header[22];
// 计算旋转后的影像宽度和高度
int new_width = abs((int)(height * sin(25 * PI / 180)) + (int)(width * cos(25 * PI / 180)));
int new_height = abs((int)(height * cos(25 * PI / 180)) + (int)(width * sin(25 * PI / 180)));
// 创建旋转后的影像文件
FILE *fp_rotated = fopen("rotated_image.bmp", "wb");
if (fp_rotated == NULL) {
printf("Failed to create rotated image file!");
return 1;
}
// 写入 BMP 文件头
fwrite(bmp_header, sizeof(unsigned char), 54, fp_rotated);
// 计算旋转后的影像在新图像中的起始坐标
int start_x = (new_width - width) / 2;
int start_y = (new_height - height) / 2;
// 读取原始影像每一行的像素值,并写入旋转后的影像
unsigned char *line = (unsigned char*)malloc(width * 3);
for (int y = 0; y < height; y++) {
fread(line, sizeof(unsigned char), width * 3, fp_src);
for (int x = 0; x < width; x++) {
// 计算旋转后的像素坐标
int new_x = (int)((x - width / 2) * cos(25 * PI / 180) + (y - height / 2) * sin(25 * PI / 180)) + start_x;
int new_y = (int)(-(x - width / 2) * sin(25 * PI / 180) + (y - height / 2) * cos(25 * PI / 180)) + start_y;
// 如果旋转后的像素坐标在新图像范围内,则写入像素值
if (new_x >= 0 && new_x < new_width && new_y >= 0 && new_y < new_height) {
fseek(fp_rotated, 54 + (new_y * new_width + new_x) * 3, SEEK_SET);
fwrite(line + x * 3, sizeof(unsigned char), 3, fp_rotated);
}
}
}
// 关闭文件指针
fclose(fp_src);
fclose(fp_rotated);
free(line);
return 0;
}
```
阅读全文