C语言生成ppm格式图像

⌚Time: 2022-10-06 00:35:43

👨‍💻Author: Jack Ge

对于ppm图像格式定义:

A PPM file consists of two parts, a header and the image data. The header consists of at least three parts normally delineated by carriage returns and/or linefeeds but the PPM specification only requires white space. The first "line" is a magic PPM identifier, it can be "P3" or "P6" (not including the double quotes!). The next line consists of the width and height of the image as ASCII numbers. The last part of the header gives the maximum value of the colour components for the pixels, this allows the format to describe more than single byte (0..255) colour values. In addition to the above required lines, a comment can be placed anywhere with a "#" character, the comment extends to the end of the line.

原文地址: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格式的图像