stbImageWrapper.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. namespace dsr {
  8. OrderedImageRgbaU8 image_stb_decode_RgbaU8(const SafePointer<uint8_t> data, int size, bool mustParse) {
  9. #ifdef SAFE_POINTER_CHECKS
  10. // If the safe pointer has debug information, use it to assert that size is within bound.
  11. data.assertInside("image_stb_decode_RgbaU8 (data)", data.getUnsafe(), (size_t)size);
  12. #endif
  13. int width, height, bpp;
  14. uint8_t *rawPixelData = stbi_load_from_memory(data.getUnsafe(), size, &width, &height, &bpp, 4);
  15. if (rawPixelData == nullptr) {
  16. if (mustParse) {
  17. throwError("An image could not be parsed!\n");
  18. }
  19. return OrderedImageRgbaU8(); // Return null
  20. }
  21. // Create a padded buffer
  22. OrderedImageRgbaU8 result = image_create_RgbaU8(width, height);
  23. // Copy the data
  24. int rowSize = width * 4;
  25. int32_t targetStride = image_getStride(result);
  26. const uint8_t *sourceRow = rawPixelData;
  27. uint8_t* targetRow = image_dangerous_getData(result);
  28. for (int32_t y = 0; y < height; y++) {
  29. // Copy a row without touching the padding
  30. memcpy(targetRow, sourceRow, rowSize);
  31. // Add stride using single byte elements
  32. targetRow += targetStride;
  33. sourceRow += rowSize;
  34. }
  35. // Free the unpadded image
  36. free((void*)rawPixelData);
  37. return result;
  38. }
  39. bool image_stb_save(const ImageRgbaU8 &image, const String& filename) {
  40. // Remove all padding before saving to avoid crashing
  41. ImageRgbaU8 unpadded = ImageRgbaU8(image_removePadding(image));
  42. return stbi_write_png(filename.toStdString().c_str(), image_getWidth(unpadded), image_getHeight(unpadded), 4, image_dangerous_getData(unpadded), image_getStride(unpadded)) != 0;
  43. }
  44. }