stbImageWrapper.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 
  2. #define STB_IMAGE_IMPLEMENTATION
  3. #include "stb_image.h"
  4. #define STB_IMAGE_WRITE_IMPLEMENTATION
  5. #include "stb_image_write.h"
  6. #include "stbImageWrapper.h"
  7. using namespace dsr;
  8. OrderedImageRgbaU8 dsr::image_stb_load_RgbaU8(const String& filename, bool mustExist) {
  9. int width, height, bpp;
  10. uint8_t *data = stbi_load(filename.toStdString().c_str(), &width, &height, &bpp, 4);
  11. if (data == 0) {
  12. if (mustExist) {
  13. // TODO: Throw an optional runtime exception
  14. printText("The image ", filename, " could not be loaded!\n");
  15. }
  16. return OrderedImageRgbaU8(); // Return null
  17. }
  18. // Create a padded buffer
  19. OrderedImageRgbaU8 result = image_create_RgbaU8(width, height);
  20. // Copy the data
  21. int rowSize = width * 4;
  22. int32_t targetStride = image_getStride(result);
  23. const uint8_t *sourceRow = data;
  24. uint8_t* targetRow = image_dangerous_getData(result);
  25. for (int32_t y = 0; y < height; y++) {
  26. // Copy a row without touching the padding
  27. memcpy(targetRow, sourceRow, rowSize);
  28. // Add stride using single byte elements
  29. targetRow += targetStride;
  30. sourceRow += rowSize;
  31. }
  32. // Free the unpadded image
  33. free(data);
  34. return result;
  35. }
  36. bool dsr::image_stb_save(const ImageRgbaU8 &image, const String& filename) {
  37. // Remove all padding before saving to avoid crashing
  38. ImageRgbaU8 unpadded = ImageRgbaU8(image_removePadding(image));
  39. return stbi_write_png(filename.toStdString().c_str(), image_getWidth(unpadded), image_getHeight(unpadded), 4, image_dangerous_getData(unpadded), image_getStride(unpadded)) != 0;
  40. }