img.c 1.9 KB

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