ImageLoad_stb.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #ifndef GUL_STB_IMAGE_LOAD_H
  2. #define GUL_STB_IMAGE_LOAD_H
  3. #include <stb_image.h>
  4. #include <gul/Image.h>
  5. #include <cstring>
  6. // C++17 includes the <filesystem> library, but
  7. // unfortunately gcc7 does not have a finalized version of it
  8. // it is in the <experimental/filesystem lib
  9. // this section includes the proper header
  10. // depending on whether the header exists and
  11. // includes that. It also sets the
  12. // nfcbn::nf namespace
  13. #if __has_include(<filesystem>)
  14. #include <filesystem>
  15. namespace gul
  16. {
  17. namespace fs = std::filesystem;
  18. }
  19. #elif __has_include(<experimental/filesystem>)
  20. #include <experimental/filesystem>
  21. namespace gul
  22. {
  23. namespace fs = std::experimental::filesystem;
  24. }
  25. #else
  26. #error There is no <filesystem> or <experimental/filesystem>
  27. #endif
  28. namespace gul
  29. {
  30. inline gul::Image loadImage(fs::path const & p, int desiredChannels=4)
  31. {
  32. int x,y,n;
  33. unsigned char *data = stbi_load(p.c_str(), &x, &y, &n, desiredChannels);
  34. gul::Image I( static_cast<uint32_t>(x), static_cast<uint32_t>(y), static_cast<uint32_t>(desiredChannels) );
  35. std::memcpy(I.data(), data, I.byteSize());
  36. stbi_image_free(data);
  37. return I;
  38. }
  39. inline gul::Image loadImage(void const* data, int len, int desiredChannels=4)
  40. {
  41. int x,y,channels;
  42. auto imgData = stbi_load_from_memory( static_cast<stbi_uc const*>(data), len, &x, &y, &channels, desiredChannels);
  43. gul::Image I( static_cast<uint32_t>(x), static_cast<uint32_t>(y), static_cast<uint32_t>(desiredChannels) );
  44. std::memcpy(I.data(), imgData, I.byteSize());
  45. stbi_image_free(imgData);
  46. return I;
  47. }
  48. }
  49. #endif