Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

C program เขียนภาพใน PGM format


PGM คือ Portable Gray Map ถ้าอยากเก็บ 2d array ใน C เป็น images ใน PNG, JPEG หรือ format อื่น ต้อง encode ข้อมูลใน format ที่กำหนดก่อนเขียนไฟล์

Netpbm format ให้ easy และ portable solution Netpbm เป็น open source graphics programs ใช้ใน Linux/Unix ทำงานบน Windows ได้ด้วย

แต่ละไฟล์เริ่มด้วย two-byte magic number ระบุประเภทไฟล์: PBM, PGM, PPM ระบุ encoding (ASCII หรือ Binary) magic number คือ P ตามด้วยตัวเลขเดี่ยว

ASCII encoding อ่านง่าย transfer ไป platform อื่นง่าย binary format มีขนาดไฟล์เล็กลงแต่อาจมี byte-order issues

How to write PGM files?

  • Set the magic number P2
  • Add whitespace
  • Add width (ASCII decimal)
  • Add Whitespace
  • Add height (ASCII decimal)
  • Add Whitespace
  • Put maximum gray value (ASCII decimal)
  • Add Whitespace
  • Width x Height gray values (0 to max) separated by whitespace top to bottom

ตัวอย่างโค้ด

#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\n"); // Writing Magic Number to the File fprintf(pgmimg, "%d %d\n", w, h); // Writing Width and Height into the file fprintf(pgmimg, "255\n"); // 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, "\n"); } fclose(pgmimg); }

The PGM image is looking like below

Output

C program เขียนภาพใน PGM format