img.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "img.h"
  2. image initialize_png(char *title, char *filename, int width, int height)
  3. {
  4. image ret;
  5. FILE *fp = NULL;
  6. fp = fopen(filename, "wb");
  7. png_structp png_ptr =
  8. png_create_write_struct(PNG_LIBPNG_VER_STRING,
  9. NULL,
  10. NULL,
  11. NULL);
  12. if (png_ptr == NULL) {
  13. fprintf(stderr, "Could not create write struct. libpng\n");
  14. }
  15. png_infop info_ptr = png_create_info_struct(png_ptr);
  16. if (info_ptr == NULL) {
  17. fprintf(stderr, "Could not create info struct. libpng\n");
  18. }
  19. if (setjmp(png_jmpbuf(png_ptr))) {
  20. fprintf(stderr, "Error during png creation\n");
  21. }
  22. png_init_io(png_ptr, fp);
  23. //Write header
  24. png_set_IHDR(png_ptr,
  25. info_ptr,
  26. width,
  27. height,
  28. 8,
  29. PNG_COLOR_TYPE_RGB,
  30. PNG_INTERLACE_NONE,
  31. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  32. if (title != NULL) {
  33. png_text title_text;
  34. title_text.compression = PNG_TEXT_COMPRESSION_NONE;
  35. title_text.key = "Title";
  36. title_text.text = title;
  37. png_set_text(png_ptr, info_ptr, &title_text, 1);
  38. }
  39. png_write_info(png_ptr, info_ptr);
  40. ret.png_ptr = png_ptr;
  41. ret.info_ptr = info_ptr;
  42. ret.width = width;
  43. ret.height = height;
  44. ret.fp = fp;
  45. return ret;
  46. }
  47. void write_image(image * img, pix_row * img_array)
  48. {
  49. png_bytep row = NULL;
  50. int x = 0, y = 0;
  51. row = (png_bytep) malloc(3 * img->width * sizeof(png_byte));
  52. for (y = 0; y < img->height; y++) {
  53. for (x = 0; x < img->width; x++) {
  54. row[x * 3 + 0] = img_array[x].p[y].r; //red
  55. row[x * 3 + 1] = img_array[x].p[y].g; // green
  56. row[x * 3 + 2] = img_array[x].p[y].b; // blue
  57. }
  58. png_write_row(img->png_ptr, row);
  59. }
  60. png_write_end(img->png_ptr, img->info_ptr);
  61. free(row);
  62. }
  63. void finish_image(image * img)
  64. {
  65. fclose(img->fp);
  66. png_free_data(img->png_ptr, img->info_ptr, PNG_FREE_ALL, -1);
  67. png_destroy_write_struct(&img->png_ptr, NULL);
  68. }