img2xlsx.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // Copyright (c) 2017-2018 Thomas Fussell
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE
  20. //
  21. // @license: http://www.opensource.org/licenses/mit-license.php
  22. // @author: see AUTHORS file
  23. #include <array>
  24. #include <iostream>
  25. #include <unordered_set>
  26. #include <vector>
  27. #include <xlnt/xlnt.hpp>
  28. #define STB_IMAGE_IMPLEMENTATION
  29. #include "stb_image.h"
  30. namespace {
  31. // This sample demonstrates the use of some complex formatting methods to create
  32. // a workbook in which each cell has a fill based on the pixels of an image
  33. // thereby appearing as a mosaic of the given image. Two methods for achieving
  34. // this effect are demonstrated: cell-level format and conditional formatting.
  35. // Clean up the code with some alias declarations
  36. using byte = std::uint8_t;
  37. using pixel = std::array<byte, 3>;
  38. using pixmap = std::vector<std::vector<pixel>>;
  39. // Specify whether the CF or cell format method should be used
  40. static const bool use_conditional_formatting = false;
  41. // Returns a 2D vector of pixels from a given filename. Accepts all file types
  42. // supported by stb_image (JPEG, PNG, TGA, BMP, PSD, GIF, HDR, PIC, PNM).
  43. pixmap load_image(const std::string &filename)
  44. {
  45. int width = 0;
  46. int height = 0;
  47. int bpp = 0;
  48. // Must be freed after use with stbi_image_free
  49. auto image_data = stbi_load(filename.c_str(), &width, &height, &bpp, 0);
  50. if (image_data == nullptr)
  51. {
  52. throw xlnt::exception("bad image or file not found: " + filename);
  53. }
  54. pixmap result;
  55. for (auto row = 0; row < height; ++row)
  56. {
  57. std::vector<pixel> row_pixels;
  58. for (auto column = 0; column < width; ++column)
  59. {
  60. auto r = image_data[row * width * bpp + column * bpp];
  61. auto g = image_data[row * width * bpp + column * bpp + 1];
  62. auto b = image_data[row * width * bpp + column * bpp + 2];
  63. auto current_pixel = pixel({ r, g, b });
  64. row_pixels.push_back(current_pixel);
  65. }
  66. result.push_back(row_pixels);
  67. }
  68. stbi_image_free(image_data);
  69. return result;
  70. }
  71. // Builds and returns a workbook in which each cell has a value
  72. // equal to the color of the pixel in the given image. A conditional format
  73. // is created for every color to set the background fill of each cell to the
  74. // color of its value. This is very slow for large images but is intended
  75. // to illustrate a realistic use of conditional formatting.
  76. xlnt::workbook build_workbook_cf(const pixmap &image)
  77. {
  78. // Create a default workbook with a single worksheet
  79. xlnt::workbook wb;
  80. // Get the active sheet (the only sheet in this case)
  81. auto ws = wb.active_sheet();
  82. // The reference to the cell which is being operated upon
  83. auto current_cell = xlnt::cell_reference("A1");
  84. // The range of cells which will be modified. This is required for conditional formats
  85. auto range = ws.range(xlnt::range_reference(1, 1,
  86. static_cast<xlnt::column_t::index_t>(image[0].size()),
  87. static_cast<xlnt::row_t>(image.size())));
  88. // Track the previously created conditonal formats so they are only created once
  89. std::unordered_set<std::string> defined_colors;
  90. // Iterate over each row in the source image
  91. for (const auto &image_row : image)
  92. {
  93. // Iterate over each pixel in the image row
  94. for (const auto &image_pixel : image_row)
  95. {
  96. // Build an xlnt compatible RGB color from the pixel byte array
  97. const auto color = xlnt::rgb_color(image_pixel[0], image_pixel[1], image_pixel[2]);
  98. // Only create the conditional format if it doesn't yet exist
  99. if (defined_colors.count(color.hex_string()) == 0)
  100. {
  101. // The condition under which the conditional format applies to a cell
  102. // In this case, the condition is satisfied when the text of the cell
  103. // contains the hex string representing the pixel color.
  104. const auto condition = xlnt::condition::text_contains(color.hex_string());
  105. // Create a new conditional format with the above condition on the image pixel range
  106. auto format = range.conditional_format(condition);
  107. // Define the fill for the conditional format
  108. format.fill(xlnt::pattern_fill().background(color));
  109. // Record the created of this CF
  110. defined_colors.insert(color.hex_string());
  111. }
  112. // Dereference the cell at the current position and set its value to the pixel color
  113. ws.cell(current_cell).value(color.hex_string());
  114. // Increment the column
  115. current_cell.column_index(current_cell.column_index() + 1);
  116. }
  117. // Reached the end of the row--move to the first column of the next row
  118. current_cell.row(current_cell.row() + 1);
  119. current_cell.column_index("A");
  120. // Show some progress, it can take a while...
  121. std::cout << current_cell.row() << " " << defined_colors.size() << std::endl;
  122. }
  123. // Return the resulting workbook
  124. return wb;
  125. }
  126. // Builds and returns a workbook in which each cell has a value
  127. // equal to the color of the pixel in the given image. To accomplish this,
  128. // a named style is created for every color in the image and is applied
  129. // to each cell corresponding to pixels of that color.
  130. xlnt::workbook build_workbook_normal(const pixmap &image)
  131. {
  132. // Create a default workbook with a single worksheet
  133. xlnt::workbook wb;
  134. // Get the active sheet (the only sheet in this case)
  135. auto ws = wb.active_sheet();
  136. // The reference to the cell which is being operated upon
  137. auto current_cell = xlnt::cell_reference("A1");
  138. // Iterate over each row in the source image
  139. for (const auto &image_row : image)
  140. {
  141. // Iterate over each pixel in the image row
  142. for (const auto &image_pixel : image_row)
  143. {
  144. // Build an xlnt compatible RGB color from the pixel byte array
  145. const auto color = xlnt::rgb_color(image_pixel[0], image_pixel[1], image_pixel[2]);
  146. // Only create the style if it doesn't yet exist in the workbook
  147. if (!wb.has_style(color.hex_string()))
  148. {
  149. // A style is constructed on a workbook by providing a unique name
  150. auto color_style = wb.create_style(color.hex_string());
  151. // Set the fill to a solid fill of the pixel color
  152. color_style.fill(xlnt::fill::solid(color));
  153. }
  154. // Dereference the cell at the current position and use the previously created color style
  155. ws.cell(current_cell).style(color.hex_string());
  156. // Increment the column
  157. current_cell.column_index(current_cell.column_index() + 1);
  158. }
  159. // Reached the end of the row--move to the first column of the next row
  160. current_cell.row(current_cell.row() + 1);
  161. current_cell.column_index("A");
  162. // Show some progress, it can take a while...
  163. std::cout << current_cell.row() << std::endl;
  164. }
  165. // Return the resulting workbook
  166. return wb;
  167. }
  168. // Builds and returns a workbook in which each cell has a value
  169. // equal to the color of the pixel in the given image using the
  170. // conditional formatting or cell-level formatting depending on
  171. // the value of use_conditional_formatting defined at the top of
  172. // this file.
  173. xlnt::workbook build_workbook(const pixmap &image)
  174. {
  175. if (use_conditional_formatting)
  176. {
  177. return build_workbook_cf(image);
  178. }
  179. else
  180. {
  181. return build_workbook_normal(image);
  182. }
  183. }
  184. } // namespace
  185. // Entry point
  186. int main(int argc, char *argv[])
  187. {
  188. // Ensure that there is a correct number of arguments
  189. if (argc < 3)
  190. {
  191. std::cout << "usage: img2xlsx <input> <output>" << std::endl;
  192. return 0;
  193. }
  194. // The first argument is the name of the input image
  195. const auto input = std::string(argv[1]);
  196. // Load the input image. An exception will be thrown if it doesn't exist.
  197. const auto image = load_image(input);
  198. // Build the workbook from the image
  199. auto workbook = build_workbook(image);
  200. // The second argument is the name of the file to save the workbook as.
  201. const auto output = std::string(argv[2]);
  202. // Save the workbook
  203. workbook.save(output);
  204. return 0;
  205. }