PNGReader.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <iostream>
  2. #include <png.h>
  3. #include <cstring>
  4. #include "utils/PNGReader.h"
  5. PNGReader::PNGReader(const char* path) : path(path), width(0), height(0), channels(0),
  6. file(fopen(path, "r")), read(nullptr), info(nullptr), rowPointers(nullptr) {
  7. if(file == nullptr) {
  8. std::cout << "file '" << path << "' cannot be read: " << strerror(errno) << "\n";
  9. return;
  10. }
  11. if(checkSignature()) {
  12. return;
  13. }
  14. read = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  15. if(read == nullptr) {
  16. std::cout << "cannot create png read data structure\n";
  17. return;
  18. }
  19. info = png_create_info_struct(read);
  20. if(info == nullptr) {
  21. std::cout << "cannot create png info structure\n";
  22. return;
  23. }
  24. if(setjmp(png_jmpbuf(read))) {
  25. std::cout << "png file '" << path << "' has used error callback\n";
  26. return;
  27. }
  28. png_init_io(read, file);
  29. png_set_sig_bytes(read, 8);
  30. png_read_info(read, info);
  31. width = png_get_image_width(read, info);
  32. height = png_get_image_height(read, info);
  33. channels = png_get_channels(read, info);
  34. }
  35. PNGReader::~PNGReader() {
  36. if(file != nullptr) {
  37. fclose(file);
  38. }
  39. if(rowPointers != nullptr) {
  40. png_free(read, rowPointers);
  41. }
  42. png_destroy_read_struct(&read, &info, nullptr);
  43. }
  44. int PNGReader::getWidth() const {
  45. return width;
  46. }
  47. int PNGReader::getHeight() const {
  48. return height;
  49. }
  50. int PNGReader::getChannels() const {
  51. return channels;
  52. }
  53. int PNGReader::getBufferSize() const {
  54. return width * height * channels;
  55. }
  56. bool PNGReader::hasError() const {
  57. return width == 0 || height == 0 || channels == 0;
  58. }
  59. bool PNGReader::checkSignature() {
  60. png_byte buffer[8];
  61. if(fread(buffer, sizeof (png_byte), 8, file) != 8) {
  62. std::cout << "cannot read signature of file '" << path << "'\n";
  63. return true;
  64. }
  65. if(png_sig_cmp(buffer, 0, 8)) {
  66. std::cout << "file '" << path << "' is not a png\n";
  67. return true;
  68. }
  69. return false;
  70. }
  71. bool PNGReader::readData(char* buffer) {
  72. if(setjmp(png_jmpbuf(read))) {
  73. std::cout << "png file '" << path << "' has used error callback\n";
  74. return true;
  75. }
  76. rowPointers = static_cast<char**> (png_malloc(read, height * (sizeof (char*))));
  77. for(int i = 0; i < height; i++) {
  78. rowPointers[i] = (buffer + i * width * channels);
  79. }
  80. png_set_rows(read, info, reinterpret_cast<png_bytepp> (rowPointers));
  81. png_read_image(read, reinterpret_cast<png_bytepp> (rowPointers));
  82. return false;
  83. }