C语言程序,用于以PGM格式写入图像
PGM是可移植灰度图。如果我们想在C语言中将二维数组存储为PNG、JPEG或任何其他图像格式的图像,则必须在写入文件之前完成大量工作才能以某种指定格式对数据进行编码。
Netpbm格式提供了一种简单易移植的解决方案。Netpbm是一个开源的图形程序包,主要用于Linux或Unix平台。它也可以在Microsoft Windows系统下运行。
每个文件以两个字节的魔数开头。此魔数用于标识文件类型。类型包括PBM、PGM、PPM等。它还标识编码(ASCII或二进制)。魔数是大写字母P后跟一个单数字。
ASCII编码允许人工读取并轻松传输到其他平台;二进制格式在文件大小方面更有效率,但可能存在本机字节序问题。
如何编写PGM文件?
- 设置魔数P2
- 添加空格(空格、制表符、回车符、换行符)
- 添加宽度,格式化为十进制ASCII字符
- 添加空格
- 添加高度,格式化为十进制ASCII字符
- 添加空格
- 添加最大灰度值,同样为十进制ASCII
- 添加空格
- 宽度 x 高度灰度值,每个都为十进制ASCII(范围在0到最大值之间),由空格分隔,从上到下。
示例代码
#include <stdio.h>
main() {
int i, j;
int w = 13, h = 13;
// This 2D array will be converted into an image The size is 13 x 13
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("my_pgmimg.pgm", "wb"); //write the file in binary mode
fprintf(pgmimg, "P2
"); // Writing Magic Number to the File
fprintf(pgmimg, "%d %d
", w, h); // Writing Width and Height into the
file
fprintf(pgmimg, "255
"); // Writing the maximum gray value
int count = 0;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
fprintf(pgmimg, "%d ", image[i][j]); //Copy gray value from
array to file
}
fprintf(pgmimg, "
");
}
fclose(pgmimg);
}PGM图像如下所示
输出

广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP