对图片的矩形区域进行颜色填充的c++代码
时间: 2023-04-07 15:01:58 浏览: 55
以下是一个简单的 C 代码示例,用于对图片的矩形区域进行颜色填充:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
unsigned char r, g, b;
} RGB;
typedef struct {
int x, y;
} Point;
typedef struct {
Point start, end;
} Rect;
void fillRect(RGB* image, int width, int height, Rect rect, RGB color) {
int x, y;
for (y = rect.start.y; y <= rect.end.y; y++) {
for (x = rect.start.x; x <= rect.end.x; x++) {
int index = y * width + x;
image[index] = color;
}
}
}
int main() {
int width = 640;
int height = 480;
RGB* image = (RGB*)malloc(width * height * sizeof(RGB));
memset(image, 0, width * height * sizeof(RGB));
Rect rect = {{100, 100}, {200, 200}};
RGB color = {255, 0, 0};
fillRect(image, width, height, rect, color);
// 保存图片到文件
FILE* fp = fopen("output.bmp", "wb");
fprintf(fp, "BM");
int fileSize = width * height * 3 + 54;
fwrite(&fileSize, 4, 1, fp);
fwrite("\0\0\0\0", 4, 1, fp);
fwrite("\x36\0\0\0", 4, 1, fp);
fwrite("\x28\0\0\0", 4, 1, fp);
fwrite(&width, 4, 1, fp);
fwrite(&height, 4, 1, fp);
fwrite("\x01\0\x18\0", 4, 1, fp);
fwrite("\0\0\0\0", 4, 1, fp);
fwrite("\0\0\0\0", 4, 1, fp);
fwrite("\0\0\0\0", 4, 1, fp);
fwrite("\0\0\0\0", 4, 1, fp);
fwrite(image, width * height * sizeof(RGB), 1, fp);
fclose(fp);
free(image);
return 0;
}
```
该代码使用 RGB 结构体表示每个像素的颜色,使用 Point 结构体表示矩形的左上角和右下角坐标,使用 Rect 结构体表示矩形。fillRect 函数接受一个 RGB 数组、图片宽度、图片高度、矩形和颜色作为参数,将矩形区域内的像素颜色设置为指定颜色。最后,代码将图片保存到 output.bmp 文件中。