-
February 17th, 2017, 12:55 AM
#1
Reading PPM format images
I’m trying to read this PPM format image, which contains an ASCII header followed by binary pixel data. The header consists of something like this:
P6
650 652
255
P6 indicates that it is a PPM image. The next two fields are the width and height of the image. The last field gives the maximum pixel value. At the end of the header is a \n and then the binary pixel data. The image is in color so there are three bytes (red, green, blue). The goal of my readPPM function is to return the pixel data in a one-dimensional array of unsigned chars, plus the width and height of the image. The goal of my writePPM function (I haven't done anything for that function yet) is to write the PPM format image to an empty file from the given information returned from my readPPM function. I'm still not sure how to make this program work so I don't store the 650 in width and 652 in height. I'll worry about that once I can actually read and write the text files.
main.cc
Code:
int main() {
//char fileName[50] = "binary_pixels.txt";
char fileName[50] = "test.ppm";
char pSix[10]; // indicates this is a PPM image
int width = 0; // width of the image
int height = 0; // heigt of the image
int maximum = 0; // maximum pixel value
int size = 128; // size of the array
// read the PPM file and store its contents inside an array and return the pointer to that array to pixelArray
unsigned char* pixelArray = readPPM(fileName, pSix, &width, &height, &maximum);
readWritePPM.cc
Code:
unsigned char* readPPM(const char* fileName, char* pSix, int* width, int* height, int* maximum) {
// open the file to read just the header reading
FILE* fr = fopen(fileName, "r");
// formatted read of header
fscanf(fr, "%s", pSix);
// check to see if it's a PPM image file
if (strncmp(pSix, "P6" , 10) != 0) {
printf("They are not the same\n");
} else {
printf("They are the same\n");
}
// read the rest of header
fscanf(fr, "%d\n %d\n", width, height);
fscanf(fr, "%d\n", maximum);
// check to see if they were stored properly
printf("PSix: %s\n", pSix);
printf("Width: %d\n", *width);
printf("Height: %d\n", *height);
printf("maximum: %d\n", *maximum);
//int size = width * height;
int size = 423800;
// allocate array for pixels
unsigned char* pixels = new unsigned char[size];
// unformatted read of binary pixel data
while (fread(pixels, sizeof(int), 128, fr)) {
printf("%s", pixels);
} // end of for loop
// close file
fclose(fr);
// return the array
return pixels;
} // end of readPPM
Last edited by 2kaud; February 18th, 2017 at 04:00 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|