📜  用C程序以PGM格式写入图像

📅  最后修改于: 2021-05-28 02:01:01             🧑  作者: Mango

PGM代表“便携式灰色地图” 。将2D数组以C格式保存为PNG,JPG或其他格式的图像将需要大量的工作,以便在写入文件之前以指定的格式对数据进行编码。
但是,Netpbm格式提供了一种简单的解决方案,并具有易于移植的特性。

Netpbm格式是Netpbm项目使用和定义的任何图形格式。便携式像素图格式(PPM),便携式灰度图格式(PGM)和便携式位图格式(PBM)是旨在在平台之间轻松交换的图像文件格式。

Netpbm是图形程序和程序库的开源软件包。它主要在Unix世界中使用,人们可以在所有主要的开放源代码操作系统发行版中找到它,但也可以在macOS和其他操作系统上使用它。它也可以在Microsoft Windows下运行。

每个文件都以两个字节的幻数(以ASCII开头)开头,该数字标识文件的类型(PBM,PGM和PPM)及其编码(ASCII或二进制)。幻数是大写字母P,后跟一个数字。

ASCII格式允许人类阅读并轻松转移到其他平台;二进制格式的文件大小更有效,但可能存在本机字节顺序问题。

在二进制格式中,PBM每像素使用1位,PGM每像素使用8位,PPM每像素使用24位:红色8位,绿色8位,蓝色8位。

PGM和PPM格式(ASCII和二进制版本)对于X和Y尺寸之后以及实际像素数据之前的最大值(黑色和白色之间的灰度数)都有一个附加参数。黑色为0,最大值为白色。有在每行的端部的换行字符。

如何写PGM文件?
文件格式如下:
1.魔术数字“ P2
2.空格(空白,TAB,CR,LF)。
3. width ,格式为十进制的ASCII字符。
4.空格。
5.再次以ASCII十进制表示的高度
6.空格。
7.最大灰度值,再次为ASCII十进制。
8.空格。
9. width X height灰色值,每个值均以ASCII十进制表示,介于0和指定的最大值之间,以栅格格式从上到下用空格隔开。

// C program to read a BMP Image and 
// write the same into a PGM Image file
#include 
  
void main()
{
    int i, j, temp = 0;
    int width = 13, height = 13;
  
    // Suppose the 2D Array to be converted to Image is as given below
    int image[13][13] = {
      { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 },
      { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31},
      { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47},
      { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63},
      { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79},
      { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 },
      { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111},
      { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127},
      { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143},
      { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159},
      { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175},
      { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191},
      { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207}
    };
  
    FILE* pgmimg;
    pgmimg = fopen("pgmimg.pgm", "wb");
  
    // Writing Magic Number to the File
    fprintf(pgmimg, "P2\n"); 
  
    // Writing Width and Height
    fprintf(pgmimg, "%d %d\n", width, height); 
  
    // Writing the maximum gray value
    fprintf(pgmimg, "255\n"); 
    int count = 0;
    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            temp = image[i][j];
  
            // Writing the gray values in the 2D array to the file
            fprintf(pgmimg, "%d ", temp);
        }
        fprintf(pgmimg, "\n");
    }
    fclose(pgmimg);
}

图像将如下所示:

参考:https://en.wikipedia.org/wiki/Netpbm_format

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。