对于ppm图像格式定义
http://paulbourke.net/dataformats/ppm/
PPM格式概述, P6 表示: 二进制PPM格式 640表示宽度, 480表示高度, 255表示颜色值范围0-255. 后面其他的为图像数据
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
int width = 640;
int height = 480;
FILE *fp;
int i, j;
char chHeader[100] = {0};
unsigned char *canvas = (unsigned char *)malloc(sizeof(unsigned char) * width * height * 3);
//初始化画布
memset(canvas, 255, width * height * 3);
//打开文件
fp = fopen("out.ppm", "w");
if(NULL == fp){
return 0;
}
//写入ppm文件头
sprintf(chHeader, "P6 %d %d 255 ", width, height);
fwrite(chHeader, sizeof(unsigned char), strlen(chHeader), fp);
//写入图像数据
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int index = i * width * 3 + j * 3;
canvas[index] = 0; // Red
canvas[index + 1] = 47; // Green
canvas[index + 2] = 167; // Blue
}
}
//保存图像数据到文件
fwrite(canvas, sizeof(unsigned char), width * height * 3, fp);
fclose(fp);
free(canvas);
return 0;
}
生成的是一副纯蓝色图片,使用irfanView软件查看ppm格式的图像
下载
iview460_x64.zip
参考
C语言 - 采用PPM格式绘图