对图片的矩形区域进行颜色填充的c++ 代码
时间: 2023-04-07 13:01:59 浏览: 135
以下是一个简单的C代码示例,用于对图片的矩形区域进行颜色填充:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int r;
int g;
int b;
} Color;
typedef struct {
int x;
int y;
int width;
int height;
} Rect;
void fillRect(Color* image, int width, int height, Rect rect, Color color) {
int x, y;
for (y = rect.y; y < rect.y + rect.height; y++) {
for (x = rect.x; x < rect.x + rect.width; x++) {
int index = y * width + x;
image[index] = color;
}
}
}
int main() {
int width = 640;
int height = 480;
Color* image = (Color*)malloc(sizeof(Color) * width * height);
memset(image, 0, sizeof(Color) * width * height);
Rect rect = { 100, 100, 200, 200 };
Color color = { 255, 0, 0 };
fillRect(image, width, height, rect, color);
// 保存图片
FILE* fp = fopen("output.ppm", "wb");
fprintf(fp, "P6\n%d %d\n255\n", width, height);
fwrite(image, sizeof(Color), width * height, fp);
fclose(fp);
free(image);
return 0;
}
```
这个程序使用了一个 `Color` 结构体来表示像素的颜色,使用一个 `Rect` 结构体来表示矩形区域。`fillRect` 函数接受一个指向图像数据的指针,以及矩形区域和颜色信息,将指定区域的像素颜色设置为指定颜色。最后,程序将生成的图像保存为 PPM 格式的文件。