pngtopng.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*- pngtopng
  2. *
  3. * COPYRIGHT: Written by John Cunningham Bowler, 2011.
  4. * To the extent possible under law, the author has waived all copyright and
  5. * related or neighboring rights to this work. This work is published from:
  6. * United States.
  7. *
  8. * Read a PNG and write it out in a fixed format, using the 'simplified API'
  9. * that was introduced in libpng-1.6.0.
  10. *
  11. * This sample code is just the code from the top of 'example.c' with some error
  12. * handling added. See example.c for more comments.
  13. */
  14. #include <stddef.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <stdio.h>
  18. /* Normally use <png.h> here to get the installed libpng, but this is done to
  19. * ensure the code picks up the local libpng implementation:
  20. */
  21. #include "../../png.h"
  22. int main(int argc, const char **argv)
  23. {
  24. int result = 1;
  25. if (argc == 3)
  26. {
  27. png_image image;
  28. /* Only the image structure version number needs to be set. */
  29. memset(&image, 0, sizeof image);
  30. image.version = PNG_IMAGE_VERSION;
  31. if (png_image_begin_read_from_file(&image, argv[1]))
  32. {
  33. png_bytep buffer;
  34. /* Change this to try different formats! If you set a colormap format
  35. * then you must also supply a colormap below.
  36. */
  37. image.format = PNG_FORMAT_RGBA;
  38. buffer = malloc(PNG_IMAGE_SIZE(image));
  39. if (buffer != NULL)
  40. {
  41. if (png_image_finish_read(&image, NULL/*background*/, buffer,
  42. 0/*row_stride*/, NULL/*colormap for PNG_FORMAT_FLAG_COLORMAP */))
  43. {
  44. if (png_image_write_to_file(&image, argv[2],
  45. 0/*convert_to_8bit*/, buffer, 0/*row_stride*/,
  46. NULL/*colormap*/))
  47. result = 0;
  48. else
  49. fprintf(stderr, "pngtopng: write %s: %s\n", argv[2],
  50. image.message);
  51. free(buffer);
  52. }
  53. else
  54. {
  55. fprintf(stderr, "pngtopng: read %s: %s\n", argv[1],
  56. image.message);
  57. /* This is the only place where a 'free' is required; libpng does
  58. * the cleanup on error and success, but in this case we couldn't
  59. * complete the read because of running out of memory.
  60. */
  61. png_image_free(&image);
  62. }
  63. }
  64. else
  65. fprintf(stderr, "pngtopng: out of memory: %lu bytes\n",
  66. (unsigned long)PNG_IMAGE_SIZE(image));
  67. }
  68. else
  69. /* Failed to read the first argument: */
  70. fprintf(stderr, "pngtopng: %s: %s\n", argv[1], image.message);
  71. }
  72. else
  73. /* Wrong number of arguments */
  74. fprintf(stderr, "pngtopng: usage: pngtopng input-file output-file\n");
  75. return result;
  76. }