ppm-graphics.c


SUBMITTED BY: okpalan86

DATE: May 10, 2023, 4:03 p.m.

FORMAT: C

SIZE: 1.1 kB

HITS: 592

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct {
  4. unsigned char r, g, b;
  5. } pixel;
  6. int main() {
  7. FILE *fp;
  8. char buf[16];
  9. int w, h, max;
  10. pixel *image;
  11. fp = fopen("image.ppm", "r");
  12. if (fp == NULL) {
  13. fprintf(stderr, "Error: Could not open file\n");
  14. exit(1);
  15. }
  16. fgets(buf, sizeof(buf), fp);
  17. if (buf[0] != 'P' || buf[1] != '6') {
  18. fprintf(stderr, "Error: Invalid file format\n");
  19. exit(1);
  20. }
  21. fscanf(fp, "%d %d", &w, &h);
  22. fscanf(fp, "%d", &max);
  23. if (max != 255) {
  24. fprintf(stderr, "Error: Unsupported color depth\n");
  25. exit(1);
  26. }
  27. fgetc(fp); // skip the newline character
  28. image = (pixel*)malloc(w * h * sizeof(pixel));
  29. if (image == NULL) {
  30. fprintf(stderr, "Error: Out of memory\n");
  31. exit(1);
  32. }
  33. fread(image, sizeof(pixel), w * h, fp);
  34. fclose(fp);
  35. // Render the image using OpenGL or other graphics library
  36. // ...
  37. free(image);
  38. return 0;
  39. }

comments powered by Disqus