#include <stdio.h> #include <io.h> #include <ctype.h> // ... FILE *pFile = fopen("result.pgm", "r"); // NOTE: With Microsoft compilers these functions might require a // leading under score (_filelength, _fileno) long file_len = filelength(fileno(pFile)); unsigned char *buffer = (unsigned char *)malloc(file_len); fread(buffer, 1, file_len, pFile); fclose(pFile); const char *header = (const char *)buffer; // Skip magic number "P4" while (isalnum(*header)) header++; // Skip white spaces while (isspace(*header)) header++; // Get width int width = atoi(header); // Skip width while (isdigit(*header)) header++; // Skip whitespace while (isspace(*header)) header++; int height = atoi(header); // Skip height while (isdigit(*header)) header++; // Skip single whitespace header++; // Pointer to first data (pixel) byte const unsigned char *data = (const unsigned char *)header; // Extra byte per row if width is not a multiple of 8 int stride = width % 8; for (int i = 0; i < height; i++) { for (int j = 0; j < width / 8; j++) { unsigned data_byte = *data++; for (int k = 0; k < 8; k++) { // Maybe the order of bits is wrong here. // If so check with mask 0x80 and shift left. // EDIT: Black is 1 and white is zero! printf("%d,", (data_byte & 1) ? 0 : 255); data_byte >>= 1; } } if (stride) { unsigned data_byte = *data++; for (int k = 0; k < stride; k++) { // Again: Maybe the order of bits is wrong here. printf("%d,", (data_byte & 1) ? 0 : 255); data_byte >>= 1; } } } free(buffer);
data_byte = (data_byte > 0x80) ? 0xff : 0;
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)