Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct {
- unsigned char red,green,blue;
- } PPMPixel;
- typedef struct {
- int x, y;
- PPMPixel *data;
- } PPMImage;
- #define CREATOR "RPFELGUEIRAS"
- #define RGB_COMPONENT_COLOR 255
- static PPMImage *readPPM(const char *filename)
- {
- char buff[16];
- PPMImage *img;
- FILE *fp;
- int rgb_comp_color;
- fp = fopen(filename, "rb");
- // DEBUG
- if (!fp) {
- fprintf(stderr, "Unable to open file '%s'\n", filename);
- exit(1);
- }
- if (!fgets(buff, sizeof(buff), fp)) {
- perror(filename);
- exit(1);
- }
- //alloc memory form image
- img = (PPMImage *)malloc(sizeof(PPMImage));
- if (!img) {
- fprintf(stderr, "Unable to allocate memory\n");
- exit(1);
- }
- //read image size information
- if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
- fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
- exit(1);
- }
- //read rgb component
- if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
- fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename);
- exit(1);
- }
- while (fgetc(fp) != '\n') ;
- //memory allocation for pixel data
- img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel));
- if (!img) {
- fprintf(stderr, "Unable to allocate memory\n");
- exit(1);
- }
- //read pixel data from file
- if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
- fprintf(stderr, "Error loading image '%s'\n", filename);
- exit(1);
- }
- fclose(fp);
- return img;
- }
- void writePPM(const char *filename, PPMImage *img)
- {
- FILE *fp = fopen(filename, "wb");
- if (!fp) {
- fprintf(stderr, "Unable to open file '%s'\n", filename);
- exit(1);
- }
- //image header
- fprintf(fp, "P6\n%d\n%d\n%d\n",img->x,img->y,RGB_COMPONENT_COLOR);
- // pixel data
- fwrite(img->data, 3 * img->x, img->y, fp);
- fclose(fp);
- }
- int main(){
- PPMImage *image;
- image = readPPM("test.ppm");
- writePPM("out.ppm",image);
- printf("Press any key...");
- getchar();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement