img.c 2.0 KB

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