ImageExport.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #include "ImageExport.h"
  2. #include "Bitmap.h"
  3. #include <boost/endian/buffers.hpp>
  4. #include <cstdio>
  5. #ifdef WITH_LIBPNG
  6. extern "C" {
  7. # include <png.h>
  8. }
  9. #endif // WITH_LIBPNG
  10. #ifdef WITH_LIBJPEG
  11. extern "C" {
  12. # include <jpeglib.h>
  13. }
  14. #endif // WITH_LIBJPEG
  15. namespace alm
  16. {
  17. #ifdef WITH_LIBPNG
  18. void exportPng(const ImageExportInfo& iei,
  19. std::function<void(float)> progressCallback,
  20. std::function<bool(void)> cancelCallback);
  21. #endif // WITH_LIBPNG
  22. #ifdef WITH_LIBJPEG
  23. void exportJpeg(const ImageExportInfo& iei,
  24. std::function<void(float)> progressCallback,
  25. std::function<bool(void)> cancelCallback);
  26. #endif // WITH_LIBJPEG
  27. void exportBmp(const ImageExportInfo& iei,
  28. std::function<void(float)> progressCallback,
  29. std::function<bool(void)> cancelCallback);
  30. const std::vector<ImageFormat> supportedImageFormats = {
  31. ImageFormat::BMP,
  32. #ifdef WITH_LIBPNG
  33. ImageFormat::PNG,
  34. #endif // WITH_LIBPNG
  35. #ifdef WITH_LIBJPEG
  36. ImageFormat::JPEG,
  37. #endif // WITH_LIBJPEG
  38. };
  39. bool supportsImageFormat(ImageFormat imgf)
  40. {
  41. for (auto f : supportedImageFormats) {
  42. if (imgf == f)
  43. return true;
  44. }
  45. return false;
  46. }
  47. ImageExportException::ImageExportException(const std::string& err) :
  48. std::runtime_error{ err }
  49. {
  50. }
  51. void exportImage(const ImageExportInfo& iei,
  52. std::function<void(float)> progressCallback,
  53. std::function<bool(void)> cancelCallback)
  54. {
  55. auto hasSuffix = [] (const std::string& path, const std::string& suffix) -> bool
  56. {
  57. return path.size() >= suffix.size() &&
  58. path.compare(path.size() - suffix.size(),
  59. suffix.size(), suffix) == 0;
  60. };
  61. if (hasSuffix(iei.path, ".bmp") ||
  62. hasSuffix(iei.path, ".dib")) {
  63. exportBmp(iei, progressCallback, cancelCallback);
  64. }
  65. #ifdef WITH_LIBPNG
  66. else if (hasSuffix(iei.path, ".png")) {
  67. exportPng(iei, progressCallback, cancelCallback);
  68. }
  69. #endif // WITH_LIBPNG
  70. #ifdef WITH_LIBJPEG
  71. else if (hasSuffix(iei.path, ".jpg") ||
  72. hasSuffix(iei.path, ".jpeg")) {
  73. exportJpeg(iei, progressCallback, cancelCallback);
  74. }
  75. #endif // WITH_LIBJPEG
  76. else {
  77. throw ImageExportException{ "Could not guess image format" };
  78. }
  79. }
  80. #ifdef WITH_LIBPNG
  81. void exportPng(const ImageExportInfo& iei,
  82. std::function<void(float)> progressCallback,
  83. std::function<bool(void)> cancelCallback)
  84. {
  85. if (iei.generator == nullptr) {
  86. throw "no generator";
  87. }
  88. progressCallback(0.0f);
  89. mnd::MandelGenerator& generator = *iei.generator;
  90. FILE* file = fopen(iei.path.c_str(), "wb");
  91. if(!file)
  92. throw ImageExportException{ std::string("could not open file '") + iei.path + "'" };
  93. png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  94. if (!png)
  95. throw ImageExportException{ "error creating png write struct" };
  96. png_infop info = png_create_info_struct(png);
  97. if (!info)
  98. throw ImageExportException{ "error creating png info struct" };
  99. if (setjmp(png_jmpbuf(png))) {
  100. png_destroy_write_struct(&png, &info);
  101. throw ImageExportException{ "error while creating png" };
  102. }
  103. png_init_io(png, file);
  104. const long width = iei.drawInfo.bWidth;
  105. const long height = iei.drawInfo.bHeight;
  106. png_set_IHDR(
  107. png,
  108. info,
  109. width, height,
  110. 8,
  111. PNG_COLOR_TYPE_RGB,
  112. PNG_INTERLACE_NONE,
  113. PNG_COMPRESSION_TYPE_DEFAULT,
  114. PNG_FILTER_TYPE_DEFAULT
  115. );
  116. png_write_info(png, info);
  117. long chunkHeight = height / 20;
  118. if (chunkHeight < 1)
  119. chunkHeight = 1;
  120. while (width * chunkHeight > 512 * 512)
  121. chunkHeight /= 2;
  122. auto rowPointers = std::make_unique<png_byte*[]>(chunkHeight);
  123. for (long chunkY = 0; chunkY < height; chunkY += chunkHeight) {
  124. auto minimum = [] (const auto& a, const auto& b) { return a < b ? a : b; };
  125. long tmpHeight = minimum(chunkHeight, height - chunkY);
  126. mnd::MandelInfo chunkInfo = iei.drawInfo;
  127. chunkInfo.bHeight = tmpHeight;
  128. chunkInfo.view.y += chunkInfo.view.height * chunkY / height;
  129. chunkInfo.view.height *= mnd::Real(tmpHeight) / height;
  130. Bitmap<float> chunk(width, tmpHeight);
  131. generator.generate(chunkInfo, chunk.pixels.get());
  132. Bitmap<RGBColor> coloredChunk = chunk.map<RGBColor>([&iei] (float i) {
  133. return i >= iei.drawInfo.maxIter ? RGBColor{ 0, 0, 0 } : iei.gradient.get(i);
  134. });
  135. for (long i = 0; i < tmpHeight; i++) {
  136. rowPointers[i] = reinterpret_cast<png_byte*>(&coloredChunk.get(0, i));
  137. }
  138. png_write_rows(png, &rowPointers[0], tmpHeight);
  139. if (chunkY < height)
  140. progressCallback(100.0f * chunkY / height);
  141. if (cancelCallback()) {
  142. fclose(file);
  143. png_destroy_write_struct(&png, &info);
  144. return;
  145. }
  146. }
  147. png_write_end(png, NULL);
  148. fclose(file);
  149. png_destroy_write_struct(&png, &info);
  150. progressCallback(100.0f);
  151. }
  152. #endif // WITH_LIBPNG
  153. #ifdef WITH_LIBJPEG
  154. void exportJpeg(const ImageExportInfo& iei,
  155. std::function<void(float)> progressCallback,
  156. std::function<bool(void)> cancelCallback)
  157. {
  158. if (iei.generator == nullptr) {
  159. throw "no generator";
  160. }
  161. progressCallback(0.0f);
  162. mnd::MandelGenerator& generator = *iei.generator;
  163. FILE* file = fopen(iei.path.c_str(), "wb");
  164. if(!file)
  165. throw ImageExportException{ std::string("could not open file '") + iei.path + "'" };
  166. const long width = iei.drawInfo.bWidth;
  167. const long height = iei.drawInfo.bHeight;
  168. struct jpeg_compress_struct jpegInfo;
  169. struct jpeg_error_mgr jerr;
  170. int rowLength = width * 3;
  171. jpegInfo.err = jpeg_std_error(&jerr);
  172. jerr.error_exit = [](j_common_ptr cinfo) {
  173. auto errmsg = std::make_unique<char[]>(JMSG_LENGTH_MAX);
  174. (cinfo->err->format_message)(cinfo, errmsg.get());
  175. throw ImageExportException{ std::string("libjpeg error: ") + errmsg.get() };
  176. };
  177. jpeg_create_compress(&jpegInfo);
  178. jpeg_stdio_dest(&jpegInfo, file);
  179. jpegInfo.image_width = width;
  180. jpegInfo.image_height = height;
  181. jpegInfo.input_components = 3;
  182. jpegInfo.in_color_space = JCS_RGB;
  183. jpeg_set_defaults(&jpegInfo);
  184. jpeg_set_quality(&jpegInfo, iei.options.jpegQuality, TRUE);
  185. jpeg_start_compress(&jpegInfo, TRUE);
  186. long chunkHeight = height / 20;
  187. if (chunkHeight < 1)
  188. chunkHeight = 1;
  189. while (width * chunkHeight > 512 * 512)
  190. chunkHeight /= 2;
  191. auto rowPointers = std::make_unique<JSAMPROW[]>(chunkHeight);
  192. for (long chunkY = 0; chunkY < height; chunkY += chunkHeight) {
  193. auto minimum = [] (const auto& a, const auto& b) { return a < b ? a : b; };
  194. long tmpHeight = minimum(chunkHeight, height - chunkY);
  195. mnd::MandelInfo chunkInfo = iei.drawInfo;
  196. chunkInfo.bHeight = tmpHeight;
  197. chunkInfo.view.y += chunkInfo.view.height * chunkY / height;
  198. chunkInfo.view.height *= mnd::Real(tmpHeight) / height;
  199. Bitmap<float> chunk(width, tmpHeight);
  200. generator.generate(chunkInfo, chunk.pixels.get());
  201. Bitmap<RGBColor> coloredChunk = chunk.map<RGBColor>([&iei] (float i) {
  202. return i >= iei.drawInfo.maxIter ? RGBColor{ 0, 0, 0 } : iei.gradient.get(i);
  203. });
  204. for (long i = 0; i < tmpHeight; i++) {
  205. rowPointers[i] = reinterpret_cast<JSAMPROW>(&coloredChunk.get(0, i));
  206. }
  207. int written = jpeg_write_scanlines(&jpegInfo, rowPointers.get(), tmpHeight);
  208. if (written < tmpHeight) {
  209. throw ImageExportException{ "error writing jpeg rows" };
  210. }
  211. if (chunkY < height)
  212. progressCallback(100.0f * chunkY / height);
  213. if (cancelCallback()) {
  214. fclose(file);
  215. jpeg_destroy_compress(&jpegInfo);
  216. return;
  217. }
  218. }
  219. jpeg_finish_compress(&jpegInfo);
  220. fclose(file);
  221. jpeg_destroy_compress(&jpegInfo);
  222. progressCallback(100.0f);
  223. }
  224. #endif // WITH_LIBJPEG
  225. void exportBmp(const ImageExportInfo& iei,
  226. std::function<void(float)> progressCallback,
  227. std::function<bool(void)> cancelCallback)
  228. {
  229. if (iei.generator == nullptr) {
  230. throw "no generator";
  231. }
  232. progressCallback(0.0f);
  233. mnd::MandelGenerator& generator = *iei.generator;
  234. FILE* file = fopen(iei.path.c_str(), "wb");
  235. if(!file)
  236. throw ImageExportException{ std::string("could not open file '") + iei.path + "'" };
  237. const long width = iei.drawInfo.bWidth;
  238. const long height = iei.drawInfo.bHeight;
  239. // bmp needs rows to be 4-byte-aligned
  240. const long rowLength = (width * 3 + 3) & ~0x03;
  241. using namespace boost::endian;
  242. const int fileHeaderSize = 14;
  243. const int infoHeaderSize = 40;
  244. const int pixelSize = rowLength * height;
  245. // file header
  246. little_int8_buf_t fhType[2];
  247. little_uint32_buf_t fhSize;
  248. little_uint16_buf_t fhReserved1;
  249. little_uint16_buf_t fhReserved2;
  250. little_uint32_buf_t fhOffset;
  251. fhType[0] = 0x42; // 'B'
  252. fhType[1] = 0x4D; // 'M'
  253. fhSize = fileHeaderSize + infoHeaderSize + pixelSize;
  254. fhReserved1 = 0;
  255. fhReserved1 = 2;
  256. fhOffset = fileHeaderSize + infoHeaderSize;
  257. // info header
  258. little_uint32_buf_t ihSize;
  259. little_int32_buf_t ihWidth;
  260. little_int32_buf_t ihHeight; // for top-down, height must be negative
  261. little_uint16_buf_t ihPlanes;
  262. little_uint16_buf_t ihBitCount;
  263. little_uint32_buf_t ihCompression; // 0 = no compression
  264. little_uint32_buf_t ihSizeImage; // for uncompressed bmps 0 can be set here
  265. little_int32_buf_t ihXPixelsPerMeter;
  266. little_int32_buf_t ihYPixelsPerMeter;
  267. little_uint32_buf_t ihClrUsed;
  268. little_uint32_buf_t ihClrImportant;
  269. ihSize = infoHeaderSize;
  270. ihWidth = width;
  271. ihHeight = -height; // for top-down, height must be negative
  272. ihPlanes = 1;
  273. ihBitCount = 24;
  274. ihCompression = 0; // 0 = no compression
  275. ihSizeImage = 0; // for uncompressed bmps 0 can be set here
  276. ihXPixelsPerMeter = 0;
  277. ihYPixelsPerMeter = 0;
  278. ihClrUsed = 0;
  279. ihClrImportant = 0;
  280. auto writeCmp = [&file] (auto& buf) {
  281. std::fwrite(&buf, sizeof(buf), 1, file);
  282. };
  283. writeCmp(fhType[0]);
  284. writeCmp(fhType[1]);
  285. writeCmp(fhSize);
  286. writeCmp(fhReserved1);
  287. writeCmp(fhReserved2);
  288. writeCmp(fhOffset);
  289. writeCmp(ihSize);
  290. writeCmp(ihWidth);
  291. writeCmp(ihHeight);
  292. writeCmp(ihPlanes);
  293. writeCmp(ihBitCount);
  294. writeCmp(ihCompression);
  295. writeCmp(ihSizeImage);
  296. writeCmp(ihXPixelsPerMeter);
  297. writeCmp(ihYPixelsPerMeter);
  298. writeCmp(ihClrUsed);
  299. writeCmp(ihClrImportant);
  300. long chunkHeight = height / 20;
  301. if (chunkHeight < 1)
  302. chunkHeight = 1;
  303. while (width * chunkHeight > 512 * 512)
  304. chunkHeight /= 2;
  305. for (long chunkY = 0; chunkY < height; chunkY += chunkHeight) {
  306. auto minimum = [] (const auto& a, const auto& b) { return a < b ? a : b; };
  307. long tmpHeight = minimum(chunkHeight, height - chunkY);
  308. mnd::MandelInfo chunkInfo = iei.drawInfo;
  309. chunkInfo.bHeight = tmpHeight;
  310. chunkInfo.view.y += chunkInfo.view.height * chunkY / height;
  311. chunkInfo.view.height *= mnd::Real(tmpHeight) / height;
  312. Bitmap<float> chunk(width, tmpHeight);
  313. generator.generate(chunkInfo, chunk.pixels.get());
  314. for (long i = 0; i < tmpHeight; i++) {
  315. for (long j = 0; j < width; j++) {
  316. float iters = chunk.get(j, i);
  317. RGBColor color =
  318. iters >= iei.drawInfo.maxIter ?
  319. RGBColor{ 0, 0, 0 } :
  320. iei.gradient.get(iters);
  321. uint8_t bgr[3] = { color.b, color.g, color.r };
  322. fwrite(bgr, 1, 3, file);
  323. }
  324. // write line padding
  325. const uint8_t zeroes[] = { 0, 0, 0, 0 };
  326. fwrite(zeroes, 1, rowLength - width * 3, file);
  327. }
  328. if (chunkY < height)
  329. progressCallback(100.0f * chunkY / height);
  330. if (cancelCallback()) {
  331. fclose(file);
  332. return;
  333. }
  334. }
  335. fflush(file);
  336. fclose(file);
  337. progressCallback(100.0f);
  338. }
  339. }