ImageReader.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma GCC diagnostic push
  2. #pragma GCC diagnostic ignored "-Wmissing-declarations"
  3. #include "libs/lodepng/lodepng.h"
  4. #pragma GCC diagnostic pop
  5. #include <stdlib.h>
  6. #include "io/ImageReader.h"
  7. #include "utils/Cleaner.h"
  8. void ImageReader::Image::clean(ColorChannel*& c) {
  9. free(c);
  10. }
  11. static void cleanRawData(ColorChannel*& c) {
  12. free(c);
  13. }
  14. static void cleanState(LodePNGState& state) {
  15. lodepng_state_cleanup(&state);
  16. }
  17. ImageReader::Image::Image() : data(nullptr) {
  18. }
  19. Error ImageReader::load(Image& image, const char* path) {
  20. Cleaner<ColorChannel*, cleanRawData> rawData(nullptr);
  21. size_t rawSize;
  22. unsigned int error = lodepng_load_file(&rawData, &rawSize, path);
  23. if(error) {
  24. Error e{"cannot load file '"};
  25. e.message.append(path).append("': ").append(lodepng_error_text(error));
  26. return e;
  27. }
  28. Cleaner<LodePNGState, cleanState> state;
  29. lodepng_state_init(&state);
  30. state->decoder.color_convert = false;
  31. error = lodepng_decode(&image.data, &image.width, &image.height, &state,
  32. rawData, rawSize);
  33. if(error) {
  34. Error e{"cannot decode file '"};
  35. e.message.append(path).append("'").append(lodepng_error_text(error));
  36. return e;
  37. }
  38. image.channels = lodepng_get_channels(&state->info_png.color);
  39. image.bitdepth = state->info_png.color.bitdepth;
  40. return {};
  41. }