Advertisement
Guest User

aaa

a guest
Mar 30th, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct {
  5.     unsigned char red,green,blue;
  6. } PPMPixel;
  7.  
  8. typedef struct {
  9.     int x, y;
  10.     PPMPixel *data;
  11. } PPMImage;
  12.  
  13. #define CREATOR "RPFELGUEIRAS"
  14. #define RGB_COMPONENT_COLOR 255
  15.  
  16. static PPMImage *readPPM(const char *filename)
  17. {
  18.     char buff[16];
  19.     PPMImage *img;
  20.     FILE *fp;
  21.     int rgb_comp_color;
  22.     fp = fopen(filename, "rb");
  23. // DEBUG
  24.     if (!fp) {
  25.         fprintf(stderr, "Unable to open file '%s'\n", filename);
  26.         exit(1);
  27.     }
  28.  
  29.     if (!fgets(buff, sizeof(buff), fp)) {
  30.         perror(filename);
  31.         exit(1);
  32.     }
  33.  
  34.     //alloc memory form image
  35.     img = (PPMImage *)malloc(sizeof(PPMImage));
  36.     if (!img) {
  37.         fprintf(stderr, "Unable to allocate memory\n");
  38.         exit(1);
  39.     }
  40.  
  41.     //read image size information
  42.     if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
  43.         fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
  44.         exit(1);
  45.     }
  46.  
  47.     //read rgb component
  48.     if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
  49.         fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename);
  50.         exit(1);
  51.     }
  52.  
  53.     while (fgetc(fp) != '\n') ;
  54.     //memory allocation for pixel data
  55.     img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel));
  56.  
  57.     if (!img) {
  58.         fprintf(stderr, "Unable to allocate memory\n");
  59.         exit(1);
  60.     }
  61.  
  62.     //read pixel data from file
  63.     if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
  64.         fprintf(stderr, "Error loading image '%s'\n", filename);
  65.         exit(1);
  66.     }
  67.  
  68.     fclose(fp);
  69.     return img;
  70. }
  71.  
  72. void writePPM(const char *filename, PPMImage *img)
  73. {
  74.     FILE *fp = fopen(filename, "wb");
  75.     if (!fp) {
  76.         fprintf(stderr, "Unable to open file '%s'\n", filename);
  77.         exit(1);
  78.     }
  79.     //image header
  80.     fprintf(fp, "P6\n%d\n%d\n%d\n",img->x,img->y,RGB_COMPONENT_COLOR);
  81.     // pixel data
  82.     fwrite(img->data, 3 * img->x, img->y, fp);
  83.     fclose(fp);
  84. }
  85.  
  86. int main(){
  87.     PPMImage *image;
  88.     image = readPPM("test.ppm");
  89.     writePPM("out.ppm",image);
  90.     printf("Press any key...");
  91.     getchar();
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement