stb_image_write.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. #include "stb_image_write.h"
  2. #define STB_IMAGE_WRITE_IMPLEMENTATION
  3. #ifdef STB_IMAGE_WRITE_IMPLEMENTATION
  4. #include <stdarg.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <math.h>
  9. #if defined(STBIW_MALLOC) && defined(STBIW_FREE) && defined(STBIW_REALLOC)
  10. // ok
  11. #elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC)
  12. // ok
  13. #else
  14. #error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC."
  15. #endif
  16. #ifndef STBIW_MALLOC
  17. #define STBIW_MALLOC(sz) malloc(sz)
  18. #define STBIW_REALLOC(p,sz) realloc(p,sz)
  19. #define STBIW_FREE(p) free(p)
  20. #endif
  21. #ifndef STBIW_MEMMOVE
  22. #define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz)
  23. #endif
  24. #ifndef STBIW_ASSERT
  25. #include <assert.h>
  26. #define STBIW_ASSERT(x) assert(x)
  27. #endif
  28. typedef unsigned int stbiw_uint32;
  29. typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
  30. static void writefv(FILE *f, const char *fmt, va_list v)
  31. {
  32. while (*fmt) {
  33. switch (*fmt++) {
  34. case ' ': break;
  35. case '1': { unsigned char x = (unsigned char) va_arg(v, int); fputc(x,f); break; }
  36. case '2': { int x = va_arg(v,int); unsigned char b[2];
  37. b[0] = (unsigned char) x; b[1] = (unsigned char) (x>>8);
  38. fwrite(b,2,1,f); break; }
  39. case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4];
  40. b[0]=(unsigned char)x; b[1]=(unsigned char)(x>>8);
  41. b[2]=(unsigned char)(x>>16); b[3]=(unsigned char)(x>>24);
  42. fwrite(b,4,1,f); break; }
  43. default:
  44. STBIW_ASSERT(0);
  45. return;
  46. }
  47. }
  48. }
  49. static void write3(FILE *f, unsigned char a, unsigned char b, unsigned char c)
  50. {
  51. unsigned char arr[3];
  52. arr[0] = a, arr[1] = b, arr[2] = c;
  53. fwrite(arr, 3, 1, f);
  54. }
  55. static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono)
  56. {
  57. unsigned char bg[3] = { 255, 0, 255}, px[3];
  58. stbiw_uint32 zero = 0;
  59. int i,j,k, j_end;
  60. if (y <= 0)
  61. return;
  62. if (vdir < 0)
  63. j_end = -1, j = y-1;
  64. else
  65. j_end = y, j = 0;
  66. for (; j != j_end; j += vdir) {
  67. for (i=0; i < x; ++i) {
  68. unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
  69. if (write_alpha < 0)
  70. fwrite(&d[comp-1], 1, 1, f);
  71. switch (comp) {
  72. case 1: fwrite(d, 1, 1, f);
  73. break;
  74. case 2: if (expand_mono)
  75. write3(f, d[0],d[0],d[0]); // monochrome bmp
  76. else
  77. fwrite(d, 1, 1, f); // monochrome TGA
  78. break;
  79. case 4:
  80. if (!write_alpha) {
  81. // composite against pink background
  82. for (k=0; k < 3; ++k)
  83. px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
  84. write3(f, px[1-rgb_dir],px[1],px[1+rgb_dir]);
  85. break;
  86. }
  87. /* FALLTHROUGH */
  88. case 3:
  89. write3(f, d[1-rgb_dir],d[1],d[1+rgb_dir]);
  90. break;
  91. }
  92. if (write_alpha > 0)
  93. fwrite(&d[comp-1], 1, 1, f);
  94. }
  95. fwrite(&zero,scanline_pad,1,f);
  96. }
  97. }
  98. static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...)
  99. {
  100. FILE *f;
  101. if (y < 0 || x < 0) return 0;
  102. f = fopen(filename, "wb");
  103. if (f) {
  104. va_list v;
  105. va_start(v, fmt);
  106. writefv(f, fmt, v);
  107. va_end(v);
  108. write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad,expand_mono);
  109. fclose(f);
  110. }
  111. return f != NULL;
  112. }
  113. int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
  114. {
  115. int pad = (-x*3) & 3;
  116. return outfile(filename,-1,-1,x,y,comp,1,(void *) data,0,pad,
  117. "11 4 22 4" "4 44 22 444444",
  118. 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
  119. 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
  120. }
  121. int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
  122. {
  123. int has_alpha = (comp == 2 || comp == 4);
  124. int colorbytes = has_alpha ? comp-1 : comp;
  125. int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3
  126. return outfile(filename, -1,-1, x, y, comp, 0, (void *) data, has_alpha, 0,
  127. "111 221 2222 11", 0,0,format, 0,0,0, 0,0,x,y, (colorbytes+has_alpha)*8, has_alpha*8);
  128. }
  129. // *************************************************************************************************
  130. // Radiance RGBE HDR writer
  131. // by Baldur Karlsson
  132. #define stbiw__max(a, b) ((a) > (b) ? (a) : (b))
  133. void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear)
  134. {
  135. int exponent;
  136. float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2]));
  137. if (maxcomp < 1e-32) {
  138. rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
  139. } else {
  140. float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp;
  141. rgbe[0] = (unsigned char)(linear[0] * normalize);
  142. rgbe[1] = (unsigned char)(linear[1] * normalize);
  143. rgbe[2] = (unsigned char)(linear[2] * normalize);
  144. rgbe[3] = (unsigned char)(exponent + 128);
  145. }
  146. }
  147. void stbiw__write_run_data(FILE *f, int length, unsigned char databyte)
  148. {
  149. unsigned char lengthbyte = (unsigned char) (length+128);
  150. STBIW_ASSERT(length+128 <= 255);
  151. fwrite(&lengthbyte, 1, 1, f);
  152. fwrite(&databyte, 1, 1, f);
  153. }
  154. void stbiw__write_dump_data(FILE *f, int length, unsigned char *data)
  155. {
  156. unsigned char lengthbyte = (unsigned char )(length & 0xff);
  157. STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code
  158. fwrite(&lengthbyte, 1, 1, f);
  159. fwrite(data, length, 1, f);
  160. }
  161. void stbiw__write_hdr_scanline(FILE *f, int width, int comp, unsigned char *scratch, const float *scanline)
  162. {
  163. unsigned char scanlineheader[4] = { 2, 2, 0, 0 };
  164. unsigned char rgbe[4];
  165. float linear[3];
  166. int x;
  167. scanlineheader[2] = (width&0xff00)>>8;
  168. scanlineheader[3] = (width&0x00ff);
  169. /* skip RLE for images too small or large */
  170. if (width < 8 || width >= 32768) {
  171. for (x=0; x < width; x++) {
  172. switch (comp) {
  173. case 4: /* fallthrough */
  174. case 3: linear[2] = scanline[x*comp + 2];
  175. linear[1] = scanline[x*comp + 1];
  176. linear[0] = scanline[x*comp + 0];
  177. break;
  178. case 2: /* fallthrough */
  179. case 1: linear[0] = linear[1] = linear[2] = scanline[x*comp + 0];
  180. break;
  181. }
  182. stbiw__linear_to_rgbe(rgbe, linear);
  183. fwrite(rgbe, 4, 1, f);
  184. }
  185. } else {
  186. int c,r;
  187. /* encode into scratch buffer */
  188. for (x=0; x < width; x++) {
  189. switch(comp) {
  190. case 4: /* fallthrough */
  191. case 3: linear[2] = scanline[x*comp + 2];
  192. linear[1] = scanline[x*comp + 1];
  193. linear[0] = scanline[x*comp + 0];
  194. break;
  195. case 2: /* fallthrough */
  196. case 1: linear[0] = linear[1] = linear[2] = scanline[x*comp + 0];
  197. break;
  198. }
  199. stbiw__linear_to_rgbe(rgbe, linear);
  200. scratch[x + width*0] = rgbe[0];
  201. scratch[x + width*1] = rgbe[1];
  202. scratch[x + width*2] = rgbe[2];
  203. scratch[x + width*3] = rgbe[3];
  204. }
  205. fwrite(scanlineheader, 4, 1, f);
  206. /* RLE each component separately */
  207. for (c=0; c < 4; c++) {
  208. unsigned char *comp = &scratch[width*c];
  209. x = 0;
  210. while (x < width) {
  211. // find first run
  212. r = x;
  213. while (r+2 < width) {
  214. if (comp[r] == comp[r+1] && comp[r] == comp[r+2])
  215. break;
  216. ++r;
  217. }
  218. if (r+2 >= width)
  219. r = width;
  220. // dump up to first run
  221. while (x < r) {
  222. int len = r-x;
  223. if (len > 128) len = 128;
  224. stbiw__write_dump_data(f, len, &comp[x]);
  225. x += len;
  226. }
  227. // if there's a run, output it
  228. if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd
  229. // find next byte after run
  230. while (r < width && comp[r] == comp[x])
  231. ++r;
  232. // output run up to r
  233. while (x < r) {
  234. int len = r-x;
  235. if (len > 127) len = 127;
  236. stbiw__write_run_data(f, len, comp[x]);
  237. x += len;
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data)
  245. {
  246. int i;
  247. FILE *f;
  248. if (y <= 0 || x <= 0 || data == NULL) return 0;
  249. f = fopen(filename, "wb");
  250. if (f) {
  251. /* Each component is stored separately. Allocate scratch space for full output scanline. */
  252. unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4);
  253. fprintf(f, "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n" );
  254. fprintf(f, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n" , y, x);
  255. for(i=0; i < y; i++)
  256. stbiw__write_hdr_scanline(f, x, comp, scratch, data + comp*i*x);
  257. STBIW_FREE(scratch);
  258. fclose(f);
  259. }
  260. return f != NULL;
  261. }
  262. /////////////////////////////////////////////////////////
  263. // PNG
  264. // stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size()
  265. #define stbiw__sbraw(a) ((int *) (a) - 2)
  266. #define stbiw__sbm(a) stbiw__sbraw(a)[0]
  267. #define stbiw__sbn(a) stbiw__sbraw(a)[1]
  268. #define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a))
  269. #define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0)
  270. #define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a)))
  271. #define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v))
  272. #define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0)
  273. #define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0)
  274. static void *stbiw__sbgrowf(void **arr, int increment, int itemsize)
  275. {
  276. int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1;
  277. void *p = STBIW_REALLOC(*arr ? stbiw__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);
  278. STBIW_ASSERT(p);
  279. if (p) {
  280. if (!*arr) ((int *) p)[1] = 0;
  281. *arr = (void *) ((int *) p + 2);
  282. stbiw__sbm(*arr) = m;
  283. }
  284. return *arr;
  285. }
  286. static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
  287. {
  288. while (*bitcount >= 8) {
  289. stbiw__sbpush(data, (unsigned char) *bitbuffer);
  290. *bitbuffer >>= 8;
  291. *bitcount -= 8;
  292. }
  293. return data;
  294. }
  295. static int stbiw__zlib_bitrev(int code, int codebits)
  296. {
  297. int res=0;
  298. while (codebits--) {
  299. res = (res << 1) | (code & 1);
  300. code >>= 1;
  301. }
  302. return res;
  303. }
  304. static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit)
  305. {
  306. int i;
  307. for (i=0; i < limit && i < 258; ++i)
  308. if (a[i] != b[i]) break;
  309. return i;
  310. }
  311. static unsigned int stbiw__zhash(unsigned char *data)
  312. {
  313. stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
  314. hash ^= hash << 3;
  315. hash += hash >> 5;
  316. hash ^= hash << 4;
  317. hash += hash >> 17;
  318. hash ^= hash << 25;
  319. hash += hash >> 6;
  320. return hash;
  321. }
  322. #define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount))
  323. #define stbiw__zlib_add(code,codebits) \
  324. (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush())
  325. #define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c)
  326. // default huffman tables
  327. #define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8)
  328. #define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9)
  329. #define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7)
  330. #define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8)
  331. #define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n))
  332. #define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n))
  333. #define stbiw__ZHASH 16384
  334. unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
  335. {
  336. static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
  337. static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
  338. static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
  339. static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
  340. unsigned int bitbuf=0;
  341. int i,j, bitcount=0;
  342. unsigned char *out = NULL;
  343. unsigned char **hash_table[stbiw__ZHASH]; // 64KB on the stack!
  344. if (quality < 5) quality = 5;
  345. stbiw__sbpush(out, 0x78); // DEFLATE 32K window
  346. stbiw__sbpush(out, 0x5e); // FLEVEL = 1
  347. stbiw__zlib_add(1,1); // BFINAL = 1
  348. stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman
  349. for (i=0; i < stbiw__ZHASH; ++i)
  350. hash_table[i] = NULL;
  351. i=0;
  352. while (i < data_len-3) {
  353. // hash next 3 bytes of data to be compressed
  354. int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3;
  355. unsigned char *bestloc = 0;
  356. unsigned char **hlist = hash_table[h];
  357. int n = stbiw__sbcount(hlist);
  358. for (j=0; j < n; ++j) {
  359. if (hlist[j]-data > i-32768) { // if entry lies within window
  360. int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i);
  361. if (d >= best) best=d,bestloc=hlist[j];
  362. }
  363. }
  364. // when hash table entry is too long, delete half the entries
  365. if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) {
  366. STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
  367. stbiw__sbn(hash_table[h]) = quality;
  368. }
  369. stbiw__sbpush(hash_table[h],data+i);
  370. if (bestloc) {
  371. // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
  372. h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1);
  373. hlist = hash_table[h];
  374. n = stbiw__sbcount(hlist);
  375. for (j=0; j < n; ++j) {
  376. if (hlist[j]-data > i-32767) {
  377. int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1);
  378. if (e > best) { // if next match is better, bail on current match
  379. bestloc = NULL;
  380. break;
  381. }
  382. }
  383. }
  384. }
  385. if (bestloc) {
  386. int d = (int) (data+i - bestloc); // distance back
  387. STBIW_ASSERT(d <= 32767 && best <= 258);
  388. for (j=0; best > lengthc[j+1]-1; ++j);
  389. stbiw__zlib_huff(j+257);
  390. if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]);
  391. for (j=0; d > distc[j+1]-1; ++j);
  392. stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5);
  393. if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]);
  394. i += best;
  395. } else {
  396. stbiw__zlib_huffb(data[i]);
  397. ++i;
  398. }
  399. }
  400. // write out final bytes
  401. for (;i < data_len; ++i)
  402. stbiw__zlib_huffb(data[i]);
  403. stbiw__zlib_huff(256); // end of block
  404. // pad with 0 bits to byte boundary
  405. while (bitcount)
  406. stbiw__zlib_add(0,1);
  407. for (i=0; i < stbiw__ZHASH; ++i)
  408. (void) stbiw__sbfree(hash_table[i]);
  409. {
  410. // compute adler32 on input
  411. unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
  412. int j=0;
  413. while (j < data_len) {
  414. for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1;
  415. s1 %= 65521, s2 %= 65521;
  416. j += blocklen;
  417. blocklen = 5552;
  418. }
  419. stbiw__sbpush(out, (unsigned char) (s2 >> 8));
  420. stbiw__sbpush(out, (unsigned char) s2);
  421. stbiw__sbpush(out, (unsigned char) (s1 >> 8));
  422. stbiw__sbpush(out, (unsigned char) s1);
  423. }
  424. *out_len = stbiw__sbn(out);
  425. // make returned pointer freeable
  426. STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len);
  427. return (unsigned char *) stbiw__sbraw(out);
  428. }
  429. unsigned int stbiw__crc32(unsigned char *buffer, int len)
  430. {
  431. static unsigned int crc_table[256];
  432. unsigned int crc = ~0u;
  433. int i,j;
  434. if (crc_table[1] == 0)
  435. for(i=0; i < 256; i++)
  436. for (crc_table[i]=i, j=0; j < 8; ++j)
  437. crc_table[i] = (crc_table[i] >> 1) ^ (crc_table[i] & 1 ? 0xedb88320 : 0);
  438. for (i=0; i < len; ++i)
  439. crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
  440. return ~crc;
  441. }
  442. #define stbiw__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)
  443. #define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
  444. #define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3])
  445. static void stbiw__wpcrc(unsigned char **data, int len)
  446. {
  447. unsigned int crc = stbiw__crc32(*data - len - 4, len+4);
  448. stbiw__wp32(*data, crc);
  449. }
  450. static unsigned char stbiw__paeth(int a, int b, int c)
  451. {
  452. int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
  453. if (pa <= pb && pa <= pc) return (unsigned char) a;
  454. if (pb <= pc) return (unsigned char) b;
  455. return (unsigned char) c;
  456. }
  457. unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
  458. {
  459. int ctype[5] = { -1, 0, 4, 2, 6 };
  460. unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
  461. unsigned char *out,*o, *filt, *zlib;
  462. signed char *line_buffer;
  463. int i,j,k,p,zlen;
  464. if (stride_bytes == 0)
  465. stride_bytes = x * n;
  466. filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0;
  467. line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; }
  468. for (j=0; j < y; ++j) {
  469. static int mapping[] = { 0,1,2,3,4 };
  470. static int firstmap[] = { 0,1,0,5,6 };
  471. int *mymap = j ? mapping : firstmap;
  472. int best = 0, bestval = 0x7fffffff;
  473. for (p=0; p < 2; ++p) {
  474. for (k= p?best:0; k < 5; ++k) {
  475. int type = mymap[k],est=0;
  476. unsigned char *z = pixels + stride_bytes*j;
  477. for (i=0; i < n; ++i)
  478. switch (type) {
  479. case 0: line_buffer[i] = z[i]; break;
  480. case 1: line_buffer[i] = z[i]; break;
  481. case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
  482. case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;
  483. case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-stride_bytes],0)); break;
  484. case 5: line_buffer[i] = z[i]; break;
  485. case 6: line_buffer[i] = z[i]; break;
  486. }
  487. for (i=n; i < x*n; ++i) {
  488. switch (type) {
  489. case 0: line_buffer[i] = z[i]; break;
  490. case 1: line_buffer[i] = z[i] - z[i-n]; break;
  491. case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
  492. case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;
  493. case 4: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;
  494. case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;
  495. case 6: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break;
  496. }
  497. }
  498. if (p) break;
  499. for (i=0; i < x*n; ++i)
  500. est += abs((signed char) line_buffer[i]);
  501. if (est < bestval) { bestval = est; best = k; }
  502. }
  503. }
  504. // when we get here, best contains the filter type, and line_buffer contains the data
  505. filt[j*(x*n+1)] = (unsigned char) best;
  506. STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n);
  507. }
  508. STBIW_FREE(line_buffer);
  509. zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory
  510. STBIW_FREE(filt);
  511. if (!zlib) return 0;
  512. // each tag requires 12 bytes of overhead
  513. out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12);
  514. if (!out) return 0;
  515. *out_len = 8 + 12+13 + 12+zlen + 12;
  516. o=out;
  517. STBIW_MEMMOVE(o,sig,8); o+= 8;
  518. stbiw__wp32(o, 13); // header length
  519. stbiw__wptag(o, "IHDR");
  520. stbiw__wp32(o, x);
  521. stbiw__wp32(o, y);
  522. *o++ = 8;
  523. *o++ = (unsigned char) ctype[n];
  524. *o++ = 0;
  525. *o++ = 0;
  526. *o++ = 0;
  527. stbiw__wpcrc(&o,13);
  528. stbiw__wp32(o, zlen);
  529. stbiw__wptag(o, "IDAT");
  530. STBIW_MEMMOVE(o, zlib, zlen);
  531. o += zlen;
  532. STBIW_FREE(zlib);
  533. stbiw__wpcrc(&o, zlen);
  534. stbiw__wp32(o,0);
  535. stbiw__wptag(o, "IEND");
  536. stbiw__wpcrc(&o,0);
  537. STBIW_ASSERT(o == out + *out_len);
  538. return out;
  539. }
  540. int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
  541. {
  542. FILE *f;
  543. int len;
  544. unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len);
  545. if (!png) return 0;
  546. f = fopen(filename, "wb");
  547. if (!f) { STBIW_FREE(png); return 0; }
  548. fwrite(png, 1, len, f);
  549. fclose(f);
  550. STBIW_FREE(png);
  551. return 1;
  552. }
  553. #endif // STB_IMAGE_WRITE_IMPLEMENTATION
  554. /* Revision history
  555. 0.98 (2015-04-08)
  556. added STBIW_MALLOC, STBIW_ASSERT etc
  557. 0.97 (2015-01-18)
  558. fixed HDR asserts, rewrote HDR rle logic
  559. 0.96 (2015-01-17)
  560. add HDR output
  561. fix monochrome BMP
  562. 0.95 (2014-08-17)
  563. add monochrome TGA output
  564. 0.94 (2014-05-31)
  565. rename private functions to avoid conflicts with stb_image.h
  566. 0.93 (2014-05-27)
  567. warning fixes
  568. 0.92 (2010-08-01)
  569. casts to unsigned char to fix warnings
  570. 0.91 (2010-07-17)
  571. first public release
  572. 0.90 first internal release
  573. */